C++ gurus and learners, we program ourselves :P all work is CC licensed

Friday, November 8

Increment Decrement Operators

C++ has a great feature of increment and decrement operators.
increment means to increase value and decrement means to decrease value.

e.g.
int apples = 10 ; 

apples = apples + 1 ;     //increments by 1

apples = apples - 1 ;     //decrements by 1 

//now apples ==10



//in C++ we can do this more easily with increment and decrement operators.



apples++; //increments

apples--; //decrements



Type of increment/decrement operators



PostFix: it changes value of variable after rest of the statement is executed.

Prefix: it changes value before any other calculation.



e.g.



int oranges = apples++;

/*

oranges will now be 10 and after execution apples value will increase by 1 so  apples=1

*/

//similarly this will result in 10 oranges and 10 apples

oranges = --apples; //first apples will be set to 10(11-1) and then oranges = apples = 10;



/* We can see in the above example that --apples/++apples or vice versa changes the value of apples. The compiler reads the following line : */
oranges = ++apples ;
// change apples = apples+1. Then set the value of Oranges = apples (new value)


/*So the statement has altered the original value of apples.
// If we do not want to change the value of apples and still set the value of oranges, then we do the following : */


oranges = apples+1;
//So the value of apples remains intact and +1 value is set for oranges :)


7 comments :

  1. your new post is pretty good :)

    ReplyDelete
  2. (y) ,,,,, Secretary ECA Software Society

    ReplyDelete
  3. It is a pleasure to have secretary ECA Software Society write for US, thumbs up (y)

    ReplyDelete
  4. Other operators are *= and += -= and /= and %= and these can be overloaded as well, we plan to introduce this concept with OOP

    ReplyDelete