Course contentsShow
← C
Lesson 167 of 1,2193. Operators and ExpressionsFree lesson

Logical NOT `!`

Logical NOT !

What you'll learn: How to use the ! operator to flip the truth value of a condition in C.

The Great "Opposite" Button

In C, the logical NOT operator—represented by the exclamation mark (!)—is the "opposite" button of programming. It takes a true value and makes it false, or takes a false value and makes it true.

Think of it like a light switch in a room. If the light is currently ON, pressing the "NOT" switch turns it OFF. If the light is OFF, pressing it turns it ON. It doesn't care about the original state; it only cares about reversing it.

How C Sees Truth

To understand !, we have to remember how C handles logic:

  • 0 is considered False.
  • Anything else (usually 1) is considered True.

When you place ! in front of a value, C evaluates it and gives you the inverse. If you have a variable called is_raining that is true, !is_raining is false. If a user is NOT logged in, we can write !is_logged_in to trigger a login prompt.

Coding the Inverse

The ! operator is a "unary" operator, meaning it only needs one thing to work on. You simply place it directly to the left of the expression you want to flip.

#include <stdio.h>

int main() {
    int engine_running = 0; // 0 means False (The engine is off)

    // Using ! to check if the engine is NOT running
    if (!engine_running) {
        printf("The engine is currently off. Ready to start!\n");
    }

    int battery_charged = 1; // 1 means True

    if (!battery_charged) {
        printf("Warning: Battery is low.\n");
    } else {
        printf("Battery is healthy.\n");
    }

    return 0;
}

In the first example, because engine_running is 0 (false), !engine_running becomes 1 (true). This allows the code inside the if block to run.

Why use it?

It helps make your code read more like natural English. Instead of writing if (is_logged_in == 0), you can write if (!is_logged_in). It is cleaner, faster to read, and reduces the chance of making a typo with double equals signs.

Key takeaway

The ! operator flips a true value to 0 and any false value (0) to 1.