0

Value of b for a=5 in following b=a++*++a

Tell me the value of a and b of incriment topic in c program

16th Oct 2019, 2:11 PM
Madhu Chennoju
Madhu Chennoju - avatar
6 Respuestas
+ 3
If you can yry with different compilers, you should get warnings and different results.
16th Oct 2019, 2:47 PM
AndreaC
AndreaC - avatar
0
Edit: I was wrong. See answers below for explanation. This particular issue concerns operator precedence. "Operator precedence determines the grouping of terms in an expression. This affects how an expression is evaluated. Certain operators have higher precedence than others;" https://en.cppreference.com/w/c/language/operator_precedence So, i believe the value of b=35 (in c11)
16th Oct 2019, 2:59 PM
Mateusz Kempa
Mateusz Kempa - avatar
0
Mateusz Kempa Can you describe how that number comes as output? (I know the output as I have test ran the code). But how the expression is parsed and which part of the expression gets higher priority to be processed?
16th Oct 2019, 3:05 PM
Ipang
0
Actually, my answer was not enterily correct. AndreaC is right. Multiple unsequenced modifications is undefined behavior. Logic i was following (so was my compiler): The ++ operator has a result and a side effect. In the expression b = a++, the result of a++ is the current value of a - that's what gets assigned to b. The side effect of a++ is to add 1 to prefix++ operator evaluates to the incremented value of its operand //hence b=5*7=35 However, in this case order of evaluation can be different and depends on your programming enviroment Conclusion: do not risk unspecified behavior. It is recommended to avoid this kind of confusing expressions. //Side conclusion: bloody C... you never stop learning it ;)
16th Oct 2019, 4:06 PM
Mateusz Kempa
Mateusz Kempa - avatar
0
Thanks for clarification Mateusz Kempa 👍
16th Oct 2019, 5:45 PM
Ipang
0
Oh ok you were actually saying that it depends on compiler uesd
17th Oct 2019, 1:10 AM
Madhu Chennoju
Madhu Chennoju - avatar