+ 1
int a=1; printf("%d",a+=(a+=3,5,a));
int a=1; printf("%d",a+=(a+=3,5,a)); What will be answer + why?
6 odpowiedzi
+ 7
Last The statement (expression)
a+=(a+=3,5,a) won't eval to
a+(5,a)
infact, 5 has no effect at all.
flow is as follow:
a+=(a+=3,5,a)
first (...) because it has highest precedence.
(a+=3,5,a)
(a = a + 3, 5, a)
(a = 1 + 3, 5, a)
(a = 4, 5, a)
(4, 5, 4) // equals 4
a = a + 4
now 'a' can be both 1 from assignment, and 4 or whatever it changed to inside (...) so
a = 1 + 4
and
a = 4 + 4
gcc does the second one (and others I tried resulting 8).
Two warnings are displayed with gcc, one is because of the issue above, another is that '5' has not any effect on the result, also it doesn't have any side effects so you can remove it altogether.
+ 2
Last
Looks like that compiler has its own way in parsing the expression. It evaluates a different result to the other compilers where I tested the OP's snippet : )
+ 1
The answer is 10. This is because the comma operator is used, which evaluates its left operand, discards the result, and then evaluates its right operand and returns it. Therefore, the statement a+=(a+=3,5,a) evaluates to a+(5,a), which is equal to a+a = 10.
+ 1
Last
Which compiler did you use to test the snippet? I tested the snippet and got 8 mostly, with warnings about operation sequence in some (in playground from SoloLearn)
+ 1
Ipang
I used Visual Studio Code with the C/C++ compiler to test the snippet.
+ 1
SD Anime this calculation leads to an undefined behavior, the answer could be anything depending on initial value and compiler interpretation. That is because you’re changing "a" variable more than once in a single expression.
https://www.sololearn.com/Discuss/3191476/?ref=app