• Forum
  • Lounge
  • What will be Output of below C Program ?

 
What will be Output of below C Program ?


int a=7,b=8;
a=a&=b&&10;
printf("%d, %d",a,b);


For description YouTube video:-
http://youtu.be/zul5JSXlNoU
Why don't you run it and find out?

http://ideone.com/
Strictly speaking, it's undefined because "a &= b && 10" is not an r-value so it can't be assigned to a variable. It does work on my gcc, and if I don't pass -Wall then it doesn't even give a warning, but you should bare in mind that it's not correct and isn't guaranteed to work on any compiler. In fact, if you enable optimisations, the compiler might just remove it -- compilers will often silently remove code that relies on undefined behaviour because the standard says a correct program will never contain undefined behaviour.
Why is that undefined? Reading from right to left since the assignment operators are right associative:

b && 10 with implicit conversion to boolean yields true or 1

then, using bitwise and compound assignment operator (1 with 7) yields 1

which is then assigned to a.

So a =1 and b = 8. What am I missing?
@chrisname why does operator&= not return a value in this case? Can you quote from the standard?
The compiler could definitely remark about a construct like a = a += 42;, even though it is defined.
I can't quote the standard, but if you pass -Wall to gcc it will say "operation [...] may be undefined". I'm fairly sure it's undefined behaviour but I may be wrong. I thought compound assignments couldn't strictly be used as r-values.

[edit] This may have changed in C++11 or may just be a C thing.

http://stackoverflow.com/questions/16520297/using-the-result-of-compound-assignment-as-an-lvalue
Last edited on
The question it is marked as a duplicate to has an answer which links to another answer, both of which state that the behavior is well defined in C++11 but not C++03, and it's completely illegal in C.
Well, that solves that mystery then.

[edit] I just remembered, this thread was about C in the first place, so I was right all along.
Last edited on
Topic archived. No new replies allowed.