Click here to Skip to main content
15,881,898 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
void main()
{
int a=10,b;
b=++a + ++a+ ++a;
printf("%d",a);
}

What I have tried:

void main()
{
int a=10,b;
b=++a + ++a+ ++a;
printf("%d",a);
}
Posted
Updated 3-Dec-17 20:33pm

Never use multiple increment/decrement on same variable inside a formula, the result is unpredictable with C.
C++
b=++a + ++a+ ++a;

Because C can rewrite code, b can be anywhere between 33 and 39.
The result will vary between compilers and depending on compiler's options.
 
Share this answer
 
Comments
CPallini 4-Dec-17 4:30am    
5.
Patrice T 4-Dec-17 4:38am    
Thank you
That's wrong!

Your program will print 13.
This is because you are printing "a" not "b".

Now, let suppose you wanted to know the result b, I assume.
First of all, it's not advised to use this kind of same pre/post incremented variables multiple times in an expression as it creates confusion as well as make it less readable.

However, let's look at why that's happening.

If you will check result of following-
C++
b=++a + ++a

you will see b will print 24 instead of expected 23. That's because, at first execution it will considers 2 operand and take them for addition. Now as pre-increment has higher priority, a's value will be incremented to 7 (due to twice pre-increment). The addition operation now will add a twice , i.e, a + a which is equals to 24.


Now, consider the case, b=++a + ++a+ ++a.
First 2 operands will be taken out and added which gives 24 as result (as we saw above) and will be stored in a temporary variable. Then it will pick the 3rd operand which 13 now and will add to the value stored in temp variable.
so, i.e, 24+13=37.

Summary:
Note: Expression evaluation starts from right end.
b=++a + ++a+ ++a;
=> b = ++a + (++a + ++a)
=> b = ++a + (++a + (a=11))
=> b = ++a + (temp=((a=12) + a))
=> b = ++a + (temp=(12+12=24))
=> b = ++a + temp)
=> b = (a=13) + temp
=> b = 13 + 24


Hope, it clarifies the doubt.

Other members of the community, please let me know if I am wrong. Please use comment section instead of down voting ;)
 
Share this answer
 
v3
Comments
Richard MacCutchan 4-Dec-17 5:24am    
You are not (completely) wrong. But you are wrong in the sense that a compiler does not guarantee to do it in this order. The rule is: do not use multiple increment decrements in a single expression.
Suvendu Shekhar Giri 4-Dec-17 6:32am    
True. Thanks!
Dinesh Sahoo 4-Dec-17 7:00am    
in some compiler the output is 39.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900