Reputation: 45
In these lines of code,
void main()
{
if(!NULL)
{
printf("one.");
}
else
{
printf("two");
}
}
the output is one. Why is that? Why is !NULL
true?
Upvotes: 3
Views: 6323
Reputation: 29
In short :-
According to C language standards ,
Non-Zero value is equivalent to TRUE
Zero & NULL are equivalent to FALSE
Hence, (! NULL) is equivalent to TRUE. So, if block is executing and one. is printed.
Upvotes: 2
Reputation: 12669
From C Standard#6.3.2.3p3 [emphasis added]
3 An integer constant expression with the value 0, or such an expression cast to type
void *
, is called a null pointer constant.66) If a null pointer constant is converted to a pointer type, the resulting pointer, called a null pointer, is guaranteed to compare unequal to a pointer to any object or function.....
....66) The macro NULL is defined in
<stddef.h>
(and other headers) as a null pointer constant; see 7.19.
From C Standard#6.5.3.3p5
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).
So, this statement
if(!NULL)
is equivalent to
if (0==NULL)
0==NULL
is evaluated to true
. Hence, you are getting output one
.
Additional:
The void
return type of main()
is not as per standard. Instead, you should use int
as return type of main()
.
Upvotes: 8
Reputation: 89
NULL is the pointer equivalent of 0. 0 is false in C and any other non-zero value is positive.
Hence if !(not operator) is applied to NULL(false), it implies that !NULL is true.
So the if condition is satisfied as true and 'one.' is printed.
Upvotes: 3