下表列出了所有C语言支持的逻辑运算符。假设变量A=1和变量B=0,则:
| 运算符 | 描述 | 示例 |
|---|---|---|
| && | 所谓逻辑与操作。如果两个操作数都非零,则条件变为真。 | (A && B) 为 false. |
| || | 所谓的逻辑或操作。如果任何两个操作数是非零,则条件变为真。 | (A || B) 为 true. |
| ! | 所谓逻辑非运算符。使用反转操作数的逻辑状态。如果条件为真,那么逻辑非操作结果为假。 | !( |
试试下面的例子就明白了所有的C编程语言提供的逻辑运算符:
#include <stdio.h>
main()
{
int a = 5;
int b = 20;
int c ;
if ( a && b )
{
printf("Line 1 - Condition is true
" );
}
if ( a || b )
{
printf("Line 2 - Condition is true
" );
}
/* lets change the value of a and b */
a = 0;
b = 10;
if ( a && b )
{
printf("Line 3 - Condition is true
" );
}
else
{
printf("Line 3 - Condition is not true
" );
}
if ( !(a && b) )
{
printf("Line 4 - Condition is true
" );
}
}
当编译和执行上面的程序就产生以下结果:
Line 1 - Condition is true Line 2 - Condition is true Line 3 - Condition is not true Line 4 - Condition is true