Click here to Skip to main content
15,886,362 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
This code gives me result 14. But I hope that result will be 12. so Why did this program give me this result?

What I have tried:

#include <stdio.h>

int main()
{
int i = 5;
int a = ++i + ++i;
printf("%d",a);

return 0;
}
Posted
Updated 23-Feb-22 21:49pm

 
Share this answer
 
 
Share this answer
 
Quote:
This code gives me result 14. But I hope that result will be 12.

This code:
C++
int a = ++i + ++i;

is in a gray zone, this means that the result is unpredictable and will depend on how it is handled by compiler. Result can be 12, 13 or 14.
Advice: Never do multiple increment/decrement on same variable in a formula.
 
Share this answer
 

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