Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I assume NULL value in comparison as the false?

I know that NULL == (void *)0 but it is mentioned that it can be represented as a value which doesn't contain all zeros. What bothers me is if those pieces of code are equivalent for all (any_type *):

any_type *val;

if (val) { ... };

and

if (val != NULL) { ... };
like image 700
Hynek -Pichi- Vychodil Avatar asked Mar 04 '15 14:03

Hynek -Pichi- Vychodil


1 Answers

Yes. You can use the macro NULL in this way. It is a null pointer constant which is equal to 0.

comp.lang.c FAQ list · Question 5.3:

When C requires the Boolean value of an expression, a false value is inferred when the expression compares equal to zero, and a true value otherwise. That is, whenever one writes

if(expr)

where expr is any expression at all, the compiler essentially acts as if it had been written as

if((expr) != 0)

Substituting the trivial pointer expression p for expr, we have

if(p)   is equivalent to    if(p != 0)

and this is a comparison context, so the compiler can tell that the (implicit) 0 is actually a null pointer constant, and use the correct null pointer value. There is no trickery involved here; compilers do work this way, and generate identical code for both constructs. The internal representation of a null pointer does not matter.


but it is mentioned that it can be represented as a value which doesn't contain all zeros.

Yes. True. But representation doesn't matter in this case:

Whenever a programmer requests a null pointer, either by writing 0 or NULL, it is the compiler's responsibility to generate whatever bit pattern the machine uses for that null pointer.

like image 164
haccks Avatar answered Sep 21 '22 01:09

haccks