Logical Operators

suggest change

Logical AND

Performs a logical boolean AND of the two operands, yielding 1 if both operands are non-zero. The result has type int.

0 && 0  /* Returns 0. */
0 && 1  /* Returns 0. */
2 && 0  /* Returns 0. */
2 && 3  /* Returns 1. */

Logical OR

Performs a logical boolean OR of the two operands, yielding 1 if either operand is non-zero. The result has type int.

0 || 0  /* Returns 0. */
0 || 1  /* Returns 1.  */
2 || 0  /* Returns 1.  */
2 || 3  /* Returns 1.  */

Logical NOT

Performs a logical negation. The result has type int. The operator yields 0 if the operand is non-zero, and 1 if the operand is zero.

!1 /* Returns 0. */
!5 /* Returns 0. */
!0 /* Returns 1. */

Short-Circuit Evaluation

There are some crucial properties common to both && and ||:

This means that:

This is important as it permits you to write code such as:

const char *name_for_value(int value)
{
    static const char *names[] = { "zero", "one", "two", "three", };
    enum { NUM_NAMES = sizeof(names) / sizeof(names[0]) };
    return (value >= 0 && value < NUM_NAMES) ? names[value] : "infinity";
}

If a negative value is passed to the function, the value >= 0 term evaluates to false and the value < NUM_NAMES term is not evaluated.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents