Link to home
Start Free TrialLog in
Avatar of cooperk50
cooperk50Flag for United States of America

asked on

C++ Increment operator

Hey guys I'm having a little trouble with this while trying to develop my program,
What expression in C++  uses the *increment* operator and what output statement it will make and why?
Can anyone help me, please.
Avatar of pepr
pepr

The built-in operator works with integer variables. It has prefix and postfix form:

i = 1;
a = i++;   // a will be 1, then i will be 2
b = ++i;   // i will be increased to 3 and then b will get the value of the new, i.e. also 3

... but the operator can also be overloaded. It means that you can define method of your class that will do what you like. The defined behaviour may be completely independent on what the original ++ does. It is also possible to distinguish between prefix and postfix version of the operator.

I am not sure what you mean by "what output statement it will make and why".
ASKER CERTIFIED SOLUTION
Avatar of itsmeandnobodyelse
itsmeandnobodyelse
Flag of Germany image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
i = 1;
ans1= i++ * i++ * i++;  (Post Increment - PoI)
i=1;
ans2= ++i * ++i * ++i; (Pre Increment  - PrI)

here needs some solid understanding to predict the ans.

in PoI value will take fist, then evaluvation next. so, ans1 will become 1*1*1=1 and after calculation Inc. evaluation will start so i will become 3 as three times incremented.

in PrI, evaluation will take first, then value next.
first all PrI operators will start evaluation so
   in first i, i will become 2
  in 2nd, i will become 3
  and in 3rd, i will become 4

now caluation starts and ans2=4*4*4 = 64 !!




>> here needs some solid understanding to predict the ans.

You can't predict the answer ... It's undefined behavior to modify the same value more than once between sequence points.

Every compiler is allowed to choose what it does in that case. For my compiler for example, ans2 has the value 36 (4 * 3 * 3), which is logical if you know how it approaches it :

        ++i * ++i * ++i  =>  (++i * ++i) * ++i

so :

        ++i;
        ++i;
        tmp = i * i;
        ++i;
        ans2 = tmp * i;

But this is just my compiler's interpretation ...



In other words : do not ever modify the same value more than once between sequence points, or you'll get some quite unpredictable behavior !