tags:

views:

149

answers:

10

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

+5  A: 

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.

Greg Hewgill
Why "roughly" ?
Felixyz
@Felixyz: You're right, that was unnecessary wording. I've added a link to more detail.
Greg Hewgill
+1  A: 

It is testing if val contains the NULL pointer. If you had said,

char * val = NULL;

if ( val ) {
  ...
}

the test would fail.

anon
You mean it would fail?
Tronic
@Tronic Of course I did - never post on SO before breakfast!
anon
+1  A: 

whether the val is a null pointer or not.

alvin
+2  A: 

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

John Knoeller
+1  A: 

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).

Pascal Cuoq
+1  A: 

It is just checking val is NULL or not .

pavun_cool
+2  A: 

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.

mnemosyn
+1  A: 

As others have said, it is checking whether the char pointer is not NULL. If you want to check if the string is not empty, try strlen.

Felix
A: 

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

uray
A: 

The above if condition is checking whether the pointer is pointing to non-null string.If that pointer points to any non-null string,then the condition will be true.Else,false.