Why does the equality operator not work with INT_MAX


8.6 The conditional operator "?:"

The conditional operator?: Is a ternary operator (the only one in ANSI C). In principle, this operator represents nothing more than a short form of the if else statement. Its syntax looks like this:

<BEDINGUNG> ? <ANWEISUNG 1> : <ANWEISUNG 2>

If the CONDITION is true, STATEMENT1 is executed. Otherwise, STATEMENT2 is executed. The program flow chart is identical to that of the ifelse instruction. For example, do you need the higher value of two numbers? With the conditional operator?: You could work like this:

This notation is equivalent to the following:

if (a> b) max = a; else max = b;

A listing should clarify the principle:

/ * max_val.c * / #include int main (void) {int a = 5, b = 10; int max; max = (a> b)? a: b; printf ("The largest value is% d \ n", max); return 0; }

Of course, it is also possible here to nest the individual expressions within one another:

/ * more_max_val.c * / #include int main (void) {int a = 8, b = 3, c = 76, big; printf ("The largest number is ...."); big = (a> b)? ((a> c)? a: c): ((b> c)? b: c); printf ("..% d \ n", big); return 0; }

Here, too, the clarity and comprehensibility of the program can suffer if there are multiple nesting. If else statements would be more suitable here. Take a closer look at the following line of code:

big = (a> b)? ((a> c)? a: c): ((b> c)? b: c);

Before the variable big is assigned a value, the following conditions are first checked: If the value of a is greater than that of b, it is checked whether the value of a is also greater than that of c. If this is the case, then a is the greatest value. If this is not the case, then c is the largest value. If, however, a is not greater than b in the first condition, it is checked whether b is greater than c. If b is greater than c, you have found the largest value. If b is not greater than c, only c remains as the largest number.

Often the conditional operator is also used like this:

printf ("Please enter a number:"); scanf ("% d", & number); printf ("The number you entered is"); (number% 2)? printf ("odd \ n"): printf ("even \ n");


your opinion

How did you like the Openbook? We always look forward to your feedback. Please send us your feedback as an e-mail to [email protected]