Why is the ternary operator used to define 1 and 0 in a macro? Why is the ternary operator used to define 1 and 0 in a macro? c c

Why is the ternary operator used to define 1 and 0 in a macro?


You are correct, in C it is tautologous. Both your particular ternary conditional and (1 > 0) are of type int.

But it would matter in C++ though, in some curious corner cases (e.g. as parameters to overloaded functions), since your ternary conditional expression is of type int, whereas (1 > 0) is of type bool.

My guess is that the author has put some thought into this, with an eye to preserving C++ compatibility.


There are linting tools that are of the opinion that the result of a comparison is boolean, and can't be used directly in arithmetic.

Not to name names or point any fingers, but PC-lint is such a linting tool.

I'm not saying they're right, but it's a possible explanation to why the code was written like that.


You'll sometimes see this in very old code, from before there was a C standard to spell out that (x > y) evaluates to numeric 1 or 0; some CPUs would rather make that evaluate to −1 or 0 instead, and some very old compilers may have just followed along, so some programmers felt they needed the extra defensiveness.

You'll sometimes also see this because similar expressions don't necessarily evaluate to numeric 1 or 0. For instance, in

#define GRENFELZ_P(flags) (((flags) & F_DO_GRENFELZ) ? 1 : 0)

the inner &-expression evaluates to either 0 or the numeric value of F_DO_GRENFELZ, which is probably not 1, so the ? 1 : 0 serves to canonicalize it. I personally think it's clearer to write that as

#define GRENFELZ_P(flags) (((flags) & F_DO_GRENFELZ) != 0)

but reasonable people can disagree. If you had a whole bunch of these in a row, testing different kinds of expressions, someone might've decided that it was more maintainable to put ? 1 : 0 on the end of all of them than to worry about which ones actually needed it.