Home > Backend Development > C++ > body text

The difference between || and && in C language

下次还敢
Release: 2024-04-28 09:40:33
Original
699 people have browsed it

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
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template