Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

while(foo) vs while(foo != NULL)

Tags:

c

while-loop

Can someone explain how while(foo) vs while(foo != NULL) are equivalent? Also:

while(!foo) vs while(foo == NULL)

I know that ! is not, but that is about all I know.

like image 911
MortalMan Avatar asked Dec 19 '22 05:12

MortalMan


1 Answers

Assuming foo is of pointer type, while (foo) and while (foo != NULL) are exactly equivalent. Both are also equivalent to while (foo != 0). (In my opinion while (foo != NULL) more clearly expresses the intent.)

In any context requiring a condition (if(), while(), a few others), the expression is treated as true if the condition compares unequal to zero, false if it compares equal to zero.

NULL is a macro that expands to an implementation-defined null pointer constant. Comparing a pointer value to NULL yields a true value for a null pointer, a false value for any non-null pointer.

The constant 0 is a null pointer constant [*]. (This doesn't mean that a null pointer has the same bit representation of 0x00000000 or something similar, though it often does; it means that a constant 0 in source code can denote a null pointer.) As you'd expect, comparing a pointer value to a null pointer constant tells you whether that pointer is a null pointer or not. In while (foo), the comparison to zero is implicit -- but it still tests whether foo is a null pointer or not.

More generally, while (foo) compares foo to 0, which is equivalent to comparing it to "zero" of the appropriate type. while (foo) is always equivalent to while (foo != 0). For a floating-point value, it's also equivalent to while (foo != 0.0). For a character value, it's equivalent to while (foo != '\0'). And, as we've seen, for a pointer value, it's equivalent to while (foo != NULL).

(In C, a comparison operator always yields an int value of 0 if the condition is false, 1 if it's true -- but any non-zero value is treated as true, via the implicit inequality comparison to zero.)

[*] A null pointer constant is defined as an integer constant expression with the value 0, or such an expression cast to void*. A null pointer constant isn't necessarily of pointer type, but converting it to pointer type yields a null pointer value. Comparing a pointer value to 0 causes the 0 to be implicitly converted to the pointer type so the comparison can be done.

like image 171
Keith Thompson Avatar answered Jan 08 '23 19:01

Keith Thompson