OiO.lk Blog C++ Why isn't this a compiler error in C/C++: #define + Ternary for function parameters
C++

Why isn't this a compiler error in C/C++: #define + Ternary for function parameters


Given the following C code:

#include <stdio.h>
#include <stdbool.h> 

#define COLOR_RED       255, 0, 0
#define COLOR_BLUE      0, 0, 255

void showColor(int r, int g, int b)
{
    printf("R: %d, G: %d, B: %d\n", r, g, b);
}

int main()
{
    showColor(true ? COLOR_RED : COLOR_BLUE);
    showColor(false ? COLOR_RED : COLOR_BLUE);

    return 0;
}

The output is not as expected:

R: 0, G: 0, B: 255
R: 0, G: 0, B: 255

It makes sense that this doesn’t work, as ternaries are run-time not compile-time.

But at the same time, it doesn’t seem like the result of the macro expansion would be valid code.

Why is this not a compiler error: showColor(true ? 255, 0, 0 : 0, 0, 255);

And why does it always resolve to the false expression of the ternary?

Just curious what the mechanism behind this forces it to always resolve to the false expression in the ternary.



You need to sign in to view this answers

Exit mobile version