Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / C

Bitwise NOT operator (~)

The ~ operator inverts an integer value's bits after integer promotions. Use it to invert masks and clear selected bits.

Version: C23; repository compiler flag, production runtime not attested

Syntax

~expression

~expression flips 0 bits to 1 and vice versa. Its operand must have integer type. The result has the operand's promoted type; the operator itself does not modify the variable.

unsigned char may promote to int: ~ does not necessarily operate only at the original type's width. For a promoted unsigned type, the result is that type's maximum minus the operand. ! is different: logical negation.

In the example, ~value & 15u restricts the result to four low bits. value & ~2u clears the bit selected by mask 2u, preserving the others.

Examples

#include <stdio.h>

int main(void)
{
    unsigned int value = 10u;
    unsigned int inverted = ~value & 15u;
    unsigned int cleared = value & ~2u;

    printf("inverted=%u\ncleared=%u\n", inverted, cleared);
    return 0;
}

Result

inverted=5
cleared=8

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