0

Why output of the code is 4 6 5

#include<stdio.h> #define max(a,b) (a>b)? a:b int main() { int x=3,y=4,z; z=max(++x,y++); printf("%d %d %d",x,y,z); return 0; } please explain how come the answer is like this !!

2nd Nov 2017, 1:57 PM
Ninad
Ninad - avatar
6 Answers
+ 6
Here's the assembly, with SoloLearn's gcc version set: https://godbolt.org/g/Eo3Lej With potentially undefined behavior (looks like reusing post and preincrement in a ternary) this may be what you have to do to answer sequence point questions (that end up being compiler-specific).
2nd Nov 2017, 2:43 PM
Kirk Schafer
Kirk Schafer - avatar
+ 4
@Kirk Schafer, on curiosity, I tried to modify the macro in Code Playground, but the output is the same, however, when I tried cout<<max(++x,y++); there was compilation error, is it possible because in that line ++x equals y++ and the macro got confused, because there's no instruction for handling a equals b? I really don't know, it's just a prediction/thought :)
2nd Nov 2017, 3:28 PM
Ipang
+ 3
@Kirk Schafer, I could be wrong, but isn't theat macro supposed to be written like #define max(a,b) a>b?a:b. instead of #define max(a,b) (a,b)?a:b
2nd Nov 2017, 2:56 PM
Ipang
+ 2
For me it gives: 5 5 5. Java: 4 5 4 Seems the compilers behavior is different, so it's better to avoid such statements in the practice.
2nd Nov 2017, 2:27 PM
Boris Batinkov
Boris Batinkov - avatar
+ 2
@lpang yeah, I thought that was curious; presenting two values successively instead of comparing. Thanks for mentioning that (details)...but I just left it as written, it can be changed if desired. cout << (9,2) << ":" << (1,9) << ":" << (1,0); output: 2:9:0
2nd Nov 2017, 3:14 PM
Kirk Schafer
Kirk Schafer - avatar
+ 2
Found a specific reference: https://gcc.gnu.org/onlinedocs/gcc/Statement-Exprs.html "For example, the “maximum” function is commonly defined as a macro in standard C as follows: #define max(a,b) ((a) > (b) ? (a) : (b)) But this definition computes either a or b twice, with bad results if the operand has side effects. In GNU C, if you know the type of the operands (here taken as int), you can define the macro safely as follows..."
2nd Nov 2017, 3:39 PM
Kirk Schafer
Kirk Schafer - avatar