Explain the output of these C codes

#include <stdio.h>
int main ()
{
	int i = 4;
	int x = ++i + ++i + ++i;
	printf ("%d", x);
	return 0;
}	

Output : 19

#include <stdio.h>
int main ()
{
	int i = 0;
	while (i++ <= 10);
	printf ("%d", i);
	return 0;
}	

Output : 12

I might be wrong(as i am applying reverse engineering) but still-
I think for first the compiler will use right precedence.
So the expression will be evaluated as ++i + (++i + ++i)
Since ++ has higher precedence so it will be ++i +(++i + 5)
then ++i +(6+5)
now maybe this addition will be with respect to memory location of i
since value of both memory locations(i) is changed to 6 instead of 6+5 ,6+6 is added and the result is 12
this 12 will be stored in a free memory location(perhaps pre-allocated by the program but not alive here)
then 7+12 is added and answer is 19.

2)in loop where i is 10 10 is compared but i is incremented to 11.So the condition fails next time.But while evaluating the condition its value changes to 12 which is printed.

2 Likes

The second explanation seems correct. Thanks.

note semicolon after while loop in 2nd Question ,and for the first question the answer does vary according to the compiler,it is either 18(5+6+7) or 19(6+6+7) FOR THE reasons as explained earlier

what’s wrong with the semi-colon?

//