Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c syntax help - very basic

Tags:

c

syntax

If we have

char *val = someString;

and then say

if(val){
    ....
}

what is the if statement actually checking here?

like image 901
haz Avatar asked Mar 06 '10 11:03

haz


3 Answers

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.

like image 192
Greg Hewgill Avatar answered Sep 22 '22 07:09

Greg Hewgill


It's checking to see if (val != 0). In C all non-zero values are true, zero is false.

like image 29
John Knoeller Avatar answered Sep 22 '22 07:09

John Knoeller


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.

like image 35
mnemosyn Avatar answered Sep 22 '22 07:09

mnemosyn