简体   繁体   中英

C program reason for the output

#include<stdio.h>

#define MAX(a,b) (a>b?a:b);

main()
{
 int x;
 x=MAX(3+2,2+7)
 printf("%d",x);
}

I checked the output of this program will come 9. Why?

因为一切都按预期进行。

...because 9 is bigger then 5? I'm guessing you're really asking how it works. (might want to look up Ternary operation) So...

#define MAX(a,b) (a>b?a:b); 

Is a Macro, the name is MAX, it takes two values "a" and "b". How it works is if a is larger than b, a is returned, else b is returned.

In this case 3+2=5=a and 2+7=9=b. So the macro boils down to:

if (5 > 9)
  return 5
else
  return 9

Then when your code is running you can think of the macro calls being replaced with that code:

void main()
{
    int x;
    if (5 > 9)
        x = 5;
    else
        x = 9;
    printf("%d", x);
}

Clearly we'll return 9, which is stored as 'x' then printed.

Does that help?

#define MAX(a,b) (a>b?a:b);

int the macro definition, the ternary if espression ?: works this way

condition ? [value if condition is true] : [value if condition is not met]

Condition is whatever expression valid in C (thus 0 is false, everything else is true)

if Condition is met, the expression evals to the first value (the one right after the ? ), or to the second value (the one right after the : ) if condition is not met

Because 2+7=9 which is bigger than 3+2=5.

Still, in general when writing that kind of macros you should be careful to enclose the parameters in parentheses in the expression that replaces the macro, to avoid the risk of someone passing an expression with operators that have lower precedence than the one you are using, thus messing up your expression.

So, normally you'll write:

#define MAX(a,b) ((a)>(b)?(a):(b));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM