haz
haz

Reputation: 97

c syntax help - very basic

If we have

char *val = someString;

and then say

if(val){
    ....
}

what is the if statement actually checking here?

Upvotes: 6

Views: 233

Answers (10)

vivek
vivek

Reputation: 141

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.

Upvotes: 0

Greg Hewgill
Greg Hewgill

Reputation: 994521

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.

Upvotes: 5

uray
uray

Reputation: 11572

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

Upvotes: 0

Felix
Felix

Reputation: 89626

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.

Upvotes: 1

mnemosyn
mnemosyn

Reputation: 46331

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.

Upvotes: 2

Pavunkumar
Pavunkumar

Reputation: 5345

It is just checking val is NULL or not .

Upvotes: 1

Pascal Cuoq
Pascal Cuoq

Reputation: 80335

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

Upvotes: 1

John Knoeller
John Knoeller

Reputation: 34198

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

Upvotes: 2

alvin
alvin

Reputation: 1196

whether the val is a null pointer or not.

Upvotes: 1

anon
anon

Reputation:

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

char * val = NULL;

if ( val ) {
  ...
}

the test would fail.

Upvotes: 1

Related Questions