I'm using an SDK for an embedded project. In this source code I found some code which at least I found peculiar. In many places in the SDK there is source code in this format:
#define ATCI_IS_LOWER( alpha_char ) ( ( (alpha_char >= ATCI_char_a) && (alpha_char <= ATCI_char_z) ) ? 1 : 0 )
#define ATCI_IS_UPPER( alpha_char ) ( ( (alpha_char >= ATCI_CHAR_A) && (alpha_char <= ATCI_CHAR_Z) ) ? 1 : 0 )
Does the use of the ternary operator here make any difference?
Isn't
#define FOO (1 > 0)
the same as
#define BAR ( (1 > 0) ? 1 : 0)
?
I tried evaluating it by using
printf("%d", FOO == BAR);
and get the result 1, so it seems that they are equal. Is there a reason to write the code like they did?
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.