+ 2
Why is the answer coming 13 in this pre increment question?
Say x= 2,then why is ++x + ++x + ++x coming as 13 in output? shouldn't it be 12? 3+4+5? Where is the one extra increment coming in C++?
1 Resposta
+ 1
1. Executing that expression depends on a) compiler and b) compiler version.
I come up with these result on my OS (Debian-based):
- With gcc (10.2.0) the result is 13. (C++)
- With openjdk (11.0.9.1) the result is 12. (Java)
I'm not sure but I think in the first part (++x + ++x), the second ++ , once act as a post-increment on first x and once again act as a pre-increment on second x. (Note: the post-increment has higher priority than plus operator.
2. Based on https://en.cppreference.com/w/cpp/language/operator_incdec
"Because of the side-effects involved, built-in increment and decrement operators must be used with care to avoid undefined behavior due to violations of sequencing rules."
I hope it helps.