C syntax help is very simple

If we have

char *val = someString; 

and then say

 if(val){ .... } 

what does the if actually check?

+7
c syntax
source share
10 answers

Your if equivalent to:

 if (val != NULL) { ... 

The comp.lang.c FAQ contains this question and answer , which explains in more detail why this is true.

+5
source share

It checks if if (val != 0) . In C, all non-zero values ​​are true, zero is false.

+2
source share

val is a pointer to char. This can be set to either -valid or invalid-. The if statement will simply check if val does not matter:

if(val)

equivalently

if(NULL != val)

equivalently

if((void*)0 != val)

However, the pointer may indicate an invalid location, for example, memory that is not in the address space of your application. Therefore, it is very important to initialize pointers to 0, otherwise they will point to undefined locations. In the worst case, this location may be valid and you will not notice an error.

+2
source share

This is a check if val contains a NULL pointer. If you said

 char * val = NULL; if ( val ) { ... } 

the test will fail.

+1
source share

whether val is a null pointer or not.

+1
source share

The assertion checks if val is what matches someString , not NULL . Usually if (v) is a shortcut for if (v!=0) .

+1
source share

This is just a check val is NULL or not.

+1
source share

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

+1
source share

val is a pointer, this operator is if (val! = 0), while 0 is also defined as NULL, so it checks to see if this pointer points to a NULL address, remember that a NULL string pointer is not the same as an empty string

0
source share

The above if condition checks if the pointer points to a nonzero string. If this pointer points to any nonzero string, then the condition will be true.Else, false.

0
source share

All Articles