Jump to content
  • Advertisement
Sign in to follow this  
doNY

An strange problem on c

This topic is 2870 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

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
Advertisement
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
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!