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?
The ternary operator is an operator that exists in some programming languages, which takes three operands rather than the typical one or two that most operators use. It provides a way to shorten a simple if else block. For example, consider the below JavaScript code.
We use the ternary operator in C to run one code when the condition is true and another code when the condition is false. For example, (age >= 18) ? printf("Can Vote") : printf("Cannot Vote");
Advantages of Ternary Operator It will improve the readability of the code. The code becomes more straightforward. Makes basic if/else logic easier to code. Instead of breaking your output building for if/else statements,you can do your if/else logic in line with output.
In computer programming, ?: is a ternary operator that is part of the syntax for basic conditional expressions in several programming languages. It is commonly referred to as the conditional operator, inline if (iif), or ternary if.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With