Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / C++

Logical negation operator !

The unary operator ! reverses its operand's truth value. The built-in operator contextually converts the operand to bool and returns bool: true for a false value and false for a true value.

Version: C++23; repository compiler flag, production runtime not attested

Syntax

!expression

The prefix operator ! appears before one operand: !expression. The built-in operator contextually converts the operand to bool, then reverses its value: !false yields true, and !true yields false. The result has type bool.

For arithmetic values, zero converts to false and every nonzero value converts to true; therefore, !0 yields true and !3 yields false. A null pointer converts to false, so !ptr yields true when ptr is null. This test does not dereference the pointer and does not prove that a non-null pointer is safe to dereference.

Do not confuse ! with ~: the former negates a truth value, while the latter flips bits. not is an alternative spelling of !. Unary operators group right-to-left, so !!count means !(!count) and, for built-in operators, produces a bool representing the truth value of count.

User-defined types can overload operator!; its behavior and result type then depend on the selected function rather than necessarily following the built-in rules. This entry targets C++23; the supplied source is an evolving working draft, not a frozen C++23 publication.

Examples

#include <iostream>

int main() {
    bool ready = false;
    int count = 3;
    int* ptr = nullptr;

    std::cout << std::boolalpha;
    std::cout << !ready << '\n';
    std::cout << !count << '\n';
    std::cout << !ptr << '\n';
    std::cout << !!count << '\n';
}

Result

true
false
true
true

The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.

Sources