Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c

#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?

like image 310
OlW Avatar asked Mar 08 '20 06:03

OlW


1 Answers

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.

like image 171
Yunnosch Avatar answered Oct 12 '22 22:10

Yunnosch