-4
#include <stdio.h>
int main()
{
    int i;

    i=1;
    printf("%d ",!i);

    i=5;
    printf("%d ",!i);

    i=0;
    printf("%d\n",!i);

    return 0;
}

I got the following output in C: 0 0 1

What is the logic behind the output?

Christian Rau
  • 45,360
  • 10
  • 108
  • 185
rohit10
  • 11
  • 2

6 Answers6

7

In C, any non zero value is considered to be a true value. So taking the logical negation with ! converts it to 0. The logical negation of 0 is 1.

jxh
  • 69,070
  • 8
  • 110
  • 193
2

In C booleans are integers where 0 is false and any other value is true.

! is NOT (as you know) so it turns any value that is not 0 into 0 and it turns 0 into 1.

Simon
  • 31,675
  • 9
  • 80
  • 92
1

i is used like a boolean value:

  • If i != 0, then !i == 0.
  • If i == 0, then !i == 1.
Lynn
  • 10,425
  • 43
  • 75
Claudio
  • 10,614
  • 4
  • 31
  • 71
1

What do you mean by "logic"?

The specific behavior of ! operator? It is defined by the language standard. It produces 0 for non-zero argument. And 1 for zero argument. That's the way it is defined.

The rationale behind such definition? Well, it is supposed to implement the logical-not behavior. Historically, in C language logical "false" is represented by zero integer values, while everything non-zero is interpreted as logical "true". So, that's what you observe in your experiment. When ! operator (or any other logical operator in C) has to generate a "true" result, it uses 1 to represent it, not just some arbitrary non-zero value.

AnT stands with Russia
  • 312,472
  • 42
  • 525
  • 765
0

You are performing a Boolean operation. The '!' is NOT an inverter as one would normally think of it. If you are looking for the inverter, use the '~'.

Lee
  • 255
  • 4
  • 16
0

! is a boolean operator that inverts the given input, from true to false and false to true. True is anything that is not zero. False is zero. So, when you notted 1 or 5, you invert a true value, which prints the integer value of false, 0. Next when you invert a false value, it prints the integer value of true (default 1)

Aswin Murugesh
  • 10,831
  • 10
  • 40
  • 69