- 1
How the output of this preincrement and postincrement equation in c is 2,2?
#include <stdio.h> int main(){ int i = 0; int j = 0; j = i++ + ++i; printf("%d %d", i,j); } output = 2, 2 here ++i = 1 then 1+i(0) = 1, hence j should be = 1, so why j = 2? and if i++ + ++i = 1+1 = 2 = j then, why i = 2? someone help me with this please.
4 ответов
0
Radib 77 this seems a question on pre increment or post increment understanding
Unfortunately, this problem is not well drafted. Generally in real world , you will not come across such situation where in same line you do pre and post increment on a single variable....
Still doing so , it results in undefined behaviour. Code behavior depends on compiler to compiler and even same compiler gives different answer at different time.
Here on your expected output case , it is evaluated like below :
++i is resulted to i as 1 as ++ has highest priority
Then i+i is 1+1 which means 2 is assigned to j
Once this line is executed, i ++ is evaluated making i from 1 to 2
+ 1
Ketan Lalcheta thanks man. Understood thank you.
0
Rather than speculating on how and why, search the net for more information around 'sequence point' and 'expression evaluation' 👍
0
preincrement (++i) increment variable before evaluating, while postincrement (i++) increment after...
j = i++ + ++i
is equal to 0 (post increment) + 2 (pre increment), because the second access to i is done after first post increment (1) and before evaluating (2)