Cover Image for Logical NOT (!) Operator in C
94 views

Logical NOT (!) Operator in C

The logical NOT operator (!) is a unary operator that is used to negate the value of a boolean expression. It is also called the “logical negation” operator. The ! operator operates on a single boolean operand, and it returns the opposite of the operand’s boolean value.

Here’s the basic syntax of the logical NOT operator:

result = !expression;
  • expression: A boolean expression that can be either true (non-zero) or false (zero).
  • result: The result of applying the logical NOT operator to the expression. It will be 1 (true) if the expression is false, and 0 (false) if the expression is true.

Here are some examples of how the logical NOT operator is used:

C
#include <stdio.h>

int main() {
    int x = 5;
    int y = 0;

    // Using the logical NOT operator to negate boolean values
    int result1 = !x;  // result1 is 0 (false) because x is non-zero (true)
    int result2 = !y;  // result2 is 1 (true) because y is zero (false)

    // Using the logical NOT operator in conditional statements
    if (!x) {
        printf("x is false (zero).\n");
    } else {
        printf("x is true (non-zero).\n");
    }

    if (!y) {
        printf("y is false (zero).\n");
    } else {
        printf("y is true (non-zero).\n");
    }

    return 0;
}

In this example:

  • result1 is assigned the value 0 because !x negates the non-zero value of x, making it 0.
  • result2 is assigned the value 1 because !y negates the zero value of y, making it 1.
  • The logical NOT operator is used in conditional statements to check the truthiness of variables. If the expression inside if evaluates to true (non-zero), then the code block inside the if is executed; otherwise, the code block inside the else is executed.

So, the logical NOT operator is useful for inverting the boolean value of an expression or variable, effectively converting true to false and vice versa.

YOU MAY ALSO LIKE...

The Tech Thunder

The Tech Thunder

The Tech Thunder


COMMENTS