#include <stdio.h>
#define big(a, b) a > b ? a : b
#define swap(a, b) temp = a; a = b; b = temp;
int main() {
int a = 3, b = 5, temp = 0;
if ((3 + big(a, b)) > b)
swap(a, b);
printf("%d %d", a, b);
}
Above code was given in a multiple choice question. I expected the answer to be 5 3. On running the code, output comes out to be 5 0. I've tried to make sense of this but my efforts have gone in vain. What's the working of this code?
Just expand the macros in the code and you will get
As the first expression
3 + ain the conditional operator is equal to6then the result of the conditional operator is the value ofathat is less thanb.So the condition of the if statement evaluates to logical false and the statement
is skipped.
As a result
awill be equal to5andbwill be equal to0.You need to use parentheses. For example