#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?
#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?
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
.
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.
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.
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 '~'.
!
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 not
ted 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)