Logical Operators in C Language

There are three types of logical operators in C language:

insert image description here
Logical operators can connect two relational expressions.

Suppose exp1 and exp2 are two simple relational expressions, such as cat > rat and debt == 1000 . Then you can state the following:

■ exp1 && exp2 is true only if both exp1 and exp2 are true.
■ exp1 || exp2 is true if either exp1 or exp2 is true or if both are true.
■ !exp1 is true if exp1 is false, and it’s false if exp1 is true.

Both && and || are sequence points.

Therefore, once an element is found that invalidates the entire expression, the evaluation will stop immediately and will not continue to calculate backwards.

For example, the statement:

while ((c = getchar()) != ' ' && c != '\n')

Read characters until the first space or newline character is encountered, and the first subexpression assigns the read character to c. The following subexpressions will also use c. If there is no guarantee of evaluation order, compile The operator may evaluate the following expression before assigning a value to c.

For another example, the statement:

if (num != 0 && 12 / num)

If num is 0, then the first subexpression is false, the entire expression is false, and the second subexpression is not evaluated further, which avoids 0 as a divisor.

Logical expressions are evaluated from left to right. Once a certain sub-expression is calculated and the value of the entire expression is found to be true or false, the calculation is stopped, so && and || are bothshort evaluation.

&& can be used for range testing, for example, the statement:

if (num > 90 && num < 100)  // 测试 num 是否大于 90 且小于 100

For another example, the statement:

if (c >= 'a' && c <= 'z')  // 判断 c 是否是一个小写字母
{
    
    
	printf("%c is a lowercase character.\n", c);
}

The above codes are only applicable to character encodings that correspond one-to-one between adjacent letters and adjacent numbers, such as ASCII.

A portable method is:

if (islower(c))  // 判断 c 是否是一个小写字母
{
    
    
	printf("%c is a lowercase character.\n", c);
}

The islower() function works regardless of the character encoding used.

Guess you like

Origin blog.csdn.net/chengkai730/article/details/132194630