By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
434,654 Members | 1,840 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 434,654 IT Pros & Developers. It's quick & easy.

the output is 1.why???

P: 2
main() { int i=5; printf(ā€œ%dā€,i=++i ==6); }
Sep 1 '10 #1
Share this Question
Share on Google+
3 Replies


100+
P: 542
Because i=++i promotes undefined behavior and the output could be any value.
Sep 1 '10 #2

Expert 100+
P: 2,400
I don't believe there is any undefined behavior here. Your snippet is equivalent to
Expand|Select|Wrap|Line Numbers
  1. main()
  2.   {
  3.   int i = 5;
  4.   i = (++i == 6);
  5.   printf(ā€œ%dā€, i);
  6.   }
The output of the == operator is either 1 or 0. In this case, it is 1 because ++i is equal to 6.

I assume the odd format string is a cut-and-paste artifact. By the way, the proper return value of main is int.
Sep 1 '10 #3

Oralloy
Expert 100+
P: 983
Folks,

All constructs of the form
Expand|Select|Wrap|Line Numbers
  1. i = i++;
  2.  
are in the realm of undefined behaviour according to the language specification.

Basically all expressions have undefined evaluation order, so an expression that has two side effects on a variable is ambiguous.
Sep 1 '10 #4

Post your reply

Sign in to post your reply or Sign up for a free account.