Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is NULL always false?

Tags:

c

null

pointers

Is it safe to assume that NULL always translates to false in C?

void *somePtr = NULL;  if (!somePtr) {   /* This will always be executed? */ } 

Or should an explicit check against the value of NULL be made?

like image 816
Sydius Avatar asked Jan 20 '09 00:01

Sydius


People also ask

Is null false or true?

The value null represents the intentional absence of any object value. It is one of JavaScript's primitive values and is treated as falsy for boolean operations.

Does null mean false?

The way you typically represent a “missing” or “invalid” value in C# is to use the “null” value of the type. Every reference type has a “null” value; that is, the reference that does not actually refer to anything.

Is null a false value in C?

Yes. NULL evaluates to false, since C considers any non-zero value true and any zero value false.

IS null always defined as 0?

The null pointer constant is always 0. The NULL macro may be defined by the implementation as a naked 0 , or a cast expression like (void *) 0 , or some other zero-valued integer expression (hence the "implementation defined" language in the standard). The null pointer value may be something other than 0.


1 Answers

Yes. NULL evaluates to false, since C considers any non-zero value true and any zero value false. NULL is essentially the zero address and is treated as such in comparisons, and I believe would be promoted to an int for the boolean check. I would expect that your code is readable to anyone familiar with C although I would probably make the check explicit.

In C and C++ programming, two null pointers are guaranteed to compare equal; ANSI C guarantees that any null pointer will be equal to 0 in a comparison with an integer type; furthermore the macro NULL is defined as a null pointer constant, that is value 0 (either as an integer type or converted to a pointer to void), so a null pointer will compare equal to NULL.

Ref: http://en.wikipedia.org/wiki/Null_pointer#Null_pointer

like image 69
tvanfosson Avatar answered Sep 21 '22 21:09

tvanfosson