If we have
char *val = someString;
and then say
if(val){
....
}
what is the if
statement actually checking here?
Your if
statement is equivalent to:
if (val != NULL) { ...
The comp.lang.c FAQ contains this question and answer which goes into a bit more detail why this is true.
It's checking to see if (val != 0)
. In C all non-zero values are true, zero is false.
val
is a pointer to a char. This can be set to any address -valid or invalid-. The if statement will just check whether val is not null:
if(val)
is equivalent to
if(NULL != val)
is equivalent to
if((void*)0 != val)
Still, the pointer can point to an invalid location, for example memory that is not in the address space of your application. Therefore, is is very important to initialize pointers to 0, otherwise they will point to undefined locations. In a worst-case scenario, that location might be valid and you won't notice the error.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With