简体   繁体   中英

Why f(0) + f(11) == f(0) in C language by conditional define f(0)

#include<stdio.h>
#define f(x) (x<10) ? 1 : 3

int main(){
    int i = f(1) + f(11);
    printf("%d", i);
    return 0;
}

Why in this case, the program output "1" but not "4".
How exactly do these two different uses of the defined macro work?

Look at what the compiler sees when pre-processing is done, with some () added for clarity:

#include<stdio.h>

int main(){
    int i = (1<10) ? 1 : (3 + (11<10) ? 1 : 3);
    printf("%d", i);
    return 0;
}

The reason for the () where I added them can be read here:
https://en.cppreference.com/w/c/language/operator_precedence

It shows that ?: has low priority and the + is pushing in to influence the result being evaluated for the first : part.

Now it should be clear.

The solution is to generously use () within macro definitions.
Comments and other answers have already provided that, I repeat for completeness:

#define f(x) (((x)<10) ? 1 : 3)

I seem to have even more () than other proposals.
Mine also protects against funny things like f(12||12) or f(0&&0) behaving weirdly.

You have to define it like

#define f(x) ((x<10) ? 1 : 3)

Note the additional parenthesis. This is because the ? operator has lower precedence than + and your macro is replaced literally, it isn't a function call that returns a result.

Macros are not the usual way to define functions, and they don't work quite like functions usually do. They do textual replacement (or, actually, token replacement, but for most purposes that's close enough. So the compiler sees main as

int main(){
    int i = (1<10) ? 1 : 3 + (11<10) ? 1 : 3;
    printf("%d", i);
    return 0;
}

Based on how the conditional operator works, this is read as int i = (1<10) ? 1 : (3 + (11<10) ? 1 : 3) int i = (1<10) ? 1 : (3 + (11<10) ? 1 : 3) . Since 1 is less than 10, this sets i to 1, and ignores the rest.

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