Hello,
what is the result of the below, and how does it work?
int i = 5;
cout << i++ * ++i << endl;
cout << i << endl;
Hello,
what is the result of the below, and how does it work?
int i = 5;
cout << i++ * ++i << endl;
cout << i << endl;
Compile it and find out. Because this looks like a homework assignment.
No, this is not a homework assignment.
int i = 5;
cout << i++ * ++i << endl;
cout << i << endl;
The integer is 5.
++ is an increment to the integer and then adds 1 to the variable if it precedes the variable. If it follows the value of the variable returns the value before it was incremented.
Most likely the value of that is 30 (5*6) but yeah, learn to compile
If this is not a homework, can we know the intention behind this question?
Are you looking for explanation on how it works? Please clarify
looking for an explanation on how it works.. as my first post states.
In short: it sets the variable i to 5, increments it twice while multiplying, outputs the result of the multiplication, and then outputs the value of i.
If you need more information, we need to be sure that it's not homework, or post in this forum (because of rule 6, to which you agreed when registering)
OK here is what happens:
I hope it is clear now.
From my point of view, this is a drill or an exercise to explain precedence.
faizlo
Hello Milhan,
The post of faizlo will explain this as best someone can, but the result of this will be:
ubuntu@ubuntu-laptop:~$ ./test
36
7
ubuntu@ubuntu-laptop:~$
Thanks,
Nathan Paulino Campos
The outputs are 36 and 7 respectively.
Associativity is right to left in this statement. Hence
cout << i++ * ++i << endl;
is actually the same as
cout << ++i * i++ << endl;
The result of this operation is undefined.
g++-4.2 gives the following error message:
warning: operation on 'i' may be undefined
The reason for this is explained at
Sequence point - Wikipedia, the free encyclopedia
Interesting. g++ 4.4.0 does not give such a warning.