What is the operator in the C.


8.5 Logical AND (&&) - logical OR (||)

You have probably already noticed that there are many operators in C. The language may be more difficult to read, but it is also faster, more versatile and more effective to program. Once you get to know the operators, you will come to appreciate them very much.

The logical OR operator (||) links operands with one another in such a way that the expression returns "true" if at least one of the operands is true.

if ((Condition1) || (Condition2)) / * at least one of the conditions is true * / else / * no condition is true * /

To do this, look at the program flow chart of the logical OR operator in Figure 8.6.

Figure 8.6 The program flow chart of the logical OR operator

Now the operator is used in the program that you used before with the logical NOT operator:

/ * logic_or.c * / #include int main (void) {int number1, number2; printf ("Please enter number 1:"); scanf ("% d", & number1); printf ("Please enter number 2:"); scanf ("% d", & number2); if ((! number1) || (! number2)) printf ("Error: One of the values ​​is equal to 0 !!! \ n"); else printf ("% d /% d =% f \ n", number1, number2, (float) number1 / number2); return 0; }

The if construction of the program looks like this:

if ((! number1) || (! number2))

In words, it would look something like this: If the value number1 is 0 OR the value number2 is 0, then the condition is true and you entered 0. If the first condition (! Number1) is already true, the second condition (! Number2) is no longer checked at all: You can also see this from the program flow chart.

The same applies to the logical AND operator (&&). The result of these linked operands only returns "true" if all operands are true. The program flow chart of the logical AND operator is shown in Figure 8.7.

Figure 8.7 Program flow chart of the logical AND operator

Again, a sample program follows for clarification:

/ * logic_and.c * / #include int main (void) {int number; printf ("Enter a value between 10 and 20:"); scanf ("% d", & number); if ((number> = 10) && (number <= 20)) printf ("Thanks for your input! \ n"); else printf ("Wrong entry! \ n"); return 0; }

In line

if ((number> = 10) && (number <= 20))

check that the number you entered has a value between 10 and 20. In words: If it is true that the number is greater than or equal to 10 AND the number is also less than or equal to 20, then the condition is true.

Of course, you can use the && operator and the || operator to link further conditions. However, you should keep an eye on the legibility of such a construct.


Note

As an alternative notation for the logical operators && and || Since the C99 standard, you can also use the macros and and or, both of which are defined in the header file .




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]