C 逻辑运算符C Logical Operators

逻辑运算符执行逻辑“与”(&&) 和逻辑“或”(||) 运算。The logical operators perform logical-AND (&&) and logical-OR ( || ) operations.



logical-AND-expression && inclusive-OR-expressionlogical-AND-expression && inclusive-OR-expression


logical-OR-expression| |logical-AND-expressionlogical-OR-expression || logical-AND-expression

逻辑运算符不执行常用算术转换。Logical operators do not perform the usual arithmetic conversions. 相反,它们根据其等效性为 0 计算每个操作数。Instead, they evaluate each operand in terms of its equivalence to 0. 逻辑运算的结果不是 0 就是 1。The result of a logical operation is either 0 or 1. 结果的类型为 intThe result's type is int.

C 逻辑运算符如下所述:The C logical operators are described below:

运算符Operator 描述Description
&& 如果两个操作数具有非零值,则逻辑“与”运算符产生值 1。The logical-AND operator produces the value 1 if both operands have nonzero values. 如果其中一个操作数等于 0,则结果为 0。If either operand is equal to 0, the result is 0. 如果逻辑“与”运算的第一个操作数等于 0,则不会计算第二个操作数。If the first operand of a logical-AND operation is equal to 0, the second operand is not evaluated.
|| 逻辑“或”运算符对其操作数执行“与或”运算。The logical-OR operator performs an inclusive-OR operation on its operands. 如果两个操作数的值均为 0,则结果为 0。The result is 0 if both operands have 0 values. 如果其中一个操作数具有非零值,则结果为 1。If either operand has a nonzero value, the result is 1. 如果逻辑“或”运算的第一个操作数具有非零值,则不会计算第二个操作数。If the first operand of a logical-OR operation has a nonzero value, the second operand is not evaluated.

逻辑“与”和逻辑“或”表达式的操作数从左到右进行计算。The operands of logical-AND and logical-OR expressions are evaluated from left to right. 如果第一个操作数的值足以确定运算的结果,则不会计算第二个操作数。If the value of the first operand is sufficient to determine the result of the operation, the second operand is not evaluated. 这称作“短路计算”。This is called "short-circuit evaluation." 第一个操作数后有一个序列点。There is a sequence point after the first operand. 有关详细信息,请参阅序列点See Sequence Points for more information.


下面的示例演示了逻辑运算符:The following examples illustrate the logical operators:

int w, x, y, z;  

if ( x < y && y < z )  
    printf( "x is less than z\n" );  

在此示例中,如果 x 小于 y,且 y 小于 z,则调用 printf 函数以输出消息。In this example, the printf function is called to print a message if x is less than y and y is less than z. 如果 x 大于 y,则不会计算第二个操作数 (y < z) 且不会输出任何内容。If x is greater than y, the second operand (y < z) is not evaluated and nothing is printed. 请注意,如果第二个操作数具有由于某个其他原因而产生的副作用,这可能会导致出现问题。Note that this could cause problems in cases where the second operand has side effects that are being relied on for some other reason.

printf( "%d" , (x == w || x == y || x == z) );  

在此示例中,如果 xwyz 相等,则 printf 函数的第二个参数的计算结果将为 true,并输出值 1。In this example, if x is equal to either w, y, or z, the second argument to the printf function evaluates to true and the value 1 is printed. 否则,它的计算结果将为 false,并打印值 0。Otherwise, it evaluates to false and the value 0 is printed. 只要其中一个条件的计算结果为 true,计算便会停止。As soon as one of the conditions evaluates to true, evaluation ceases.

请参阅See Also

逻辑“与”运算符:&& Logical AND Operator: &&
逻辑“或”运算符:||Logical OR Operator: ||