Home > database >  how logical NOT operator works in c?
how logical NOT operator works in c?

Time:01-29

How the logical NOT operator ! actually works in c? How it turns all non-zero int into 0 and vice-versa?

For example:

#include <stdio.h>

void main() {
    if(!(-76))
        printf("I won't print anything");

    if(!(2))
        printf("I will also not print anything");
}

doesn't print anything, which could mean -76 and 2 was turned into zero...

So, I tried this:

#include <stdio.h>

void main() {
    int x = !4;
    printf("%d", x);
}

which indeed printed 0

and now I don't get how, is it flipping all the bits to 0 or what?

CodePudding user response:

Most CPU architectures include an instruction to compare to zero; or even check the result against zero for most operations run on the processor. How this construct is implemented will differ from compiler to compiler.

For example, in x86, there are two instructions: JZ and JNZ: jump zero and jump not zero, which can be used if your test is an if statement. If the last value looked at was zero, jump (or don't jump) to a new instruction.

Given this, it's trivial to implement int x = !4; at assembly level as a jump if 4 is zero or not, though this particular example would be likely calculated at compile time, since all values are constant.

Additionally, most versions of the x86 instruction set support the SETZ instruction directly, which will set a register directly to 1 or 0, based on whether the processors zero flag is currently set. This can be used to implement the logical NOT operation directly.

CodePudding user response:

6.5.3.3 Unary arithmetic operators

Constraints

1 The operand of the unary or - operator shall have arithmetic type; of the ~ operator, integer type; of the ! operator, scalar type.

Semantics
...
5 The result of the logical negation operator ! is 0 if the value of its operand compares unequal to 0, 1 if the value of its operand compares equal to 0. The result has type int. The expression !E is equivalent to (0==E).

C 202x Working Draft

So, that's what language definition says should happen; if the expression x evaluates to non-zero, then the expression !x should evaluate to zero; if x evaluates to zero, then !x should evaluate to 1. The bits of the operand are not affected.

How that's accomplished in the machine code is up to the specific implementation; it depends on the available instruction set, the compiler, and various other factors such that no one answer works everywhere. It could translate to a branch statement, it could take advantage of specialized instructions, etc.

  • Related