Sign in to follow this  
doNY

An strange problem on c

Recommended Posts

I was typing these C language codes below:

#include <stdio.h>

int main()
{
int i,j;
i=3;
j=(++i)+(++i)+(i++);
printf("%d\n",j);
return 0;
}


In my opinion first,the result was 14.But it's 15!
and then I type the similar codes on Java.The result was 14.

More than that,I test another C language code:

#include <stdio.h>

int main()
{
int i,j;
i=3;
j=(++i)+(++i)+(++i);//changes
printf("%d\n",j);
return 0;
}



and the result was 16 but 14 on Java and 18 on C++ compiler.

How does that happen?!

Share this post


Link to post
Share on other sites
In short, the statement "j=(++i)+(++i)+(i++)" doesn't have any Sequence Points. The compiler is free to evaluate the parts of that statement in any order it sees fit, resulting in really wonky answers depending on the compiler and optimizations being used. Usually the lack of a sequence point on operators like + is a good thing, since it lets the compiler best optimize the expression by choosing what side of the + to evaluate first.

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this