+ 4
int i=0; cout<<++i + ++i + ++i<<endl; why output of this code is 7?
int i =0; cout<<++i + ++i + ++i<<endl; can anyone explain why output of this code is 7 ?
7 Answers
+ 3
Compiler Bug for sure. Try the following:
int i = 0;
cout << ++i + ++i + ++i << endl;
cout << "i = " << i;
Interestingly i is still 3. In fact the only thing which happens here is adding 1 + 2 + 3. How should this ever become anything else than 6?
Faced a similar issue with:
int i = 4;
cout << ++i + i++;
Which is 10 (as expected) in visual studio but 11 on Sololearn. Even worse here as some challenges exist which "teach" you wrong here. In this case even if you try all the different possible combinations with wrong operator precedence this expression never can exceed 10.
EDIT:
Maybe I've to re-think.
As already mentioned by tutalia trying this example in VS2017 gives 9. Gcc gives 7 while clang gives 6 plus following warning:
```
C++ Sandbox.cpp:13:16: warning: multiple unsequenced modifications to 'i' [-Wunsequenced]
std::cout << ++i + ++i + ++i << std::endl;
^ ~~
```
Maybe this is just about implementation defined behavior.
Anyway looks like sololearn is using gcc to compile the stuff.
Even for the other example mentioned gcc gives 11 (instead of 10 which I would have expected. clang provides 10 there.
+ 2
logically according to the definition of prefix increment operator it should be 6.
i compiled the same code on java it resulted in 6..
whereas in c++ it resulted in 7
I think this is a compiler's bug
+ 2
Harshit, i agree with you. May be this is a compilers bug or each compiler has it's own implementation for preincrement logic.
By the way even if i compiled same code with different c++ compilers results are are also different. Output is like below:
c++ gcc : 7
clang: 6
vc++: 9
It seems very strange to me.
+ 2
int i =0;
cout<<
++i // i becomes 1
+ // before this addition i becomes 2 and only then is added and becomes 3
++i // here i becomes 2 and only then previous ^ addition operator works(see
// operators precedence)
// i is 3 now
+ // before this addition i becomes 4 and only then is added and becomes 7
++i // here i becomes 4 and only then previous ^ addition operator works
<<endl;
+ 2
Anna, i think you're right
the operator precedence is right to left for increment decrement operator
and left to right for addition and substraction
0
it really is strange
0
that's interesting finding..đđđ