Home  >  Article  >  Backend Development  >  The difference between || and && in C language

The difference between || and && in C language

下次还敢
下次还敢Original
2024-04-27 23:18:30696browse

In C language, the || operator is true if at least one of its operands is true, while the && operator is true if all of its operands are true. || ignores subsequent true operands, while && stops evaluation when a false operand is found. Their precedence is higher than comparison operators but lower than assignment operators.

The difference between || and && in C language

The difference between || and && in C language

In C language, && and || are logical Operator used to combine two or more Boolean expressions.

|| (Logical OR)

|| The operator checks whether at least one of its operands is true:

  • If any If one operand is true, the result is true.
  • The result is false only if all operands are false.

&(logical AND)

&& operator checks whether its operands are both true:

  • If all operations If the numbers are all true, the result is true.
  • The result is false only if either operand is false.

Difference

|| and && is their behavior with the False operand:

  • | | Even if one operand is true, subsequent operands are ignored.
  • && The result is evaluated only if all operands are true.

Example

int a = 1, b = 0, c = 1;

printf("a || b || c: %d\n", a || b || c); // 输出:1
printf("a & b & c: %d\n", a & b & c); // 输出:0

In the first example, because a is true, the || operator ignores the values ​​of b and c.

In the second example, because b is false, the && operator stops evaluating and returns False even though c is true.

Priority

|| and && have higher precedence than comparison operators (==, !=, >, <, >=, < ;=), but lower than the assignment operator (=).

The above is the detailed content of The difference between || and && in C language. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn