if we have
char *val = someString;
and then say
if(val){
....
}
what is the if statement actually checking here?
thanks
edit : Thanks for all the replys
if we have
char *val = someString;
and then say
if(val){
....
}
what is the if statement actually checking here?
thanks
edit : Thanks for all the replys
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 is testing if val contains the NULL pointer. If you had said,
char * val = NULL;
if ( val ) {
...
}
the test would fail.
It's checking to see if (val != 0)
. In C all non-zero values are true, zero is false.
The statement is checking if val
, which is the same as someString
, is non-NULL
. Generally if (v)
is a shortcut for if (v!=0)
.
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.
val is a pointer, that statement is equal to if(val !=0), whereas 0 is also defined as NULL, so it will check whether that pointer is pointing to NULL address, keep in mind that NULL string pointer is not the same as empty string