Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 277
Viktor S Avatar asked Mar 31 '17 11:03

Viktor S


People also ask

What is a ternary operator why do we use it?

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.

Why do we use ternary operator in C?

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");

What are the advantage of using ternary operator?

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.

Which is called ternary operator 1 point?

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.


2 Answers

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.

like image 167
Bathsheba Avatar answered Oct 22 '22 20:10

Bathsheba


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.

like image 41
unwind Avatar answered Oct 22 '22 19:10

unwind