+ 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?

15th Feb 2023, 5:27 AM
SD Anime
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.
16th Feb 2023, 12:14 PM
Tina
Tina - avatar
+ 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 : )
16th Feb 2023, 7:18 AM
Ipang
+ 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.
15th Feb 2023, 6:06 PM
Last
Last - avatar
+ 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)
16th Feb 2023, 4:30 AM
Ipang
+ 1
Ipang I used Visual Studio Code with the C/C++ compiler to test the snippet.
16th Feb 2023, 7:09 AM
Last
Last - avatar
+ 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
16th Feb 2023, 8:23 AM
Tina
Tina - avatar