Tom's Guide | Tom's Hardware | Tom's Games
![]() |
![]() |
![]() |
increment in c language can be written as
i = i + 1. or as i++ or as ++i.but what if i want to add 2 to the i. and write it as post or prefix, like i++

The key thing to remember about post and pre-increment/decrement operators is how they behave when used with assignemnts. The prefix increment/decrement operators do their incrementing/decrementing before assigning the value. The postfix operators assign the original value first and then increment/decrement the value. For example:
int i = 1;
int k = 1;k = ++i;
cout << "k = " << k << "; i = " << i << endl;// Reset original values:
i = 1;
k = 1;k = i++;
cout << "k = " << k << "; i = " << i << endl;... would print out
k = 2; i = 2
k = 1; i = 2For your problem, you can use the increment operator "+=".
// Add 2 to i and assign the result back
// into i:
i += 2;you can even use assignments like this in an expression:
k = (i += 2) + 5;
which is equivalent to the two statements
i = i + 2;
k = i + 5;The other thing you can do is use parentheses if you want to (actually, I try to use parenthese all the time to make expressions more comprehensible):
k = (i++)++;//<--Increment twice, but assign
// original i to k first
k = ++(++i);//<--Increment i twice first, and
// then assign i to k.....Personally, I think the multiple-parentheses-increment/decrement operator thing is bad style (because it's hard to read). I'd go with the += operator approach before that, or better -- just use more than one statement. It's easy to write clever compact code -- the trick is being able to read it and figure it out 6 months later :-). Simplicity is the key to successful programming.
--- Bryan

Another possibility is to overload the ++ operator to add two instead of one (there are two plus signs after all). You can also choose your own operator name. I'm not a real big fan of overloading, but if the situation calls for it as the best solution, it should be used (sez me anyway). If you are never going to use the "++" in your app, overloading is your obvious choice, other than that, it depends on conventions, preferences... an OO dude would say "overload"; a front line coder with a deadline might say otherwise.
notice a flag is sent as a param to designate post.
const Counter& Counter::operator++ ();
Counter Counter::operator++ (int);

![]() |
Fortran 77 Mac toolbox pr...
|
Simple project (extremely...
|

This post is quite old and has been locked from receiving new replies. Please create a new posting instead.
| Ads by Google |