What is the difference between str==NULL and str[0]=='\0' in C?

john picture john · Nov 30, 2011 · Viewed 11.1k times · Source

I want to know the difference between str == NULL and str[0] == '\0':

int convert_to_float(char *str, double *num)
{
    if ((str == NULL) || (str[0] == '\0'))
        return(-1);

    *num = strtod(str, (char **)NULL);
    return(0);
}

I'm using gcc on Linux.

Answer

Mysticial picture Mysticial · Nov 30, 2011

str==NULL tells you whether the pointer is NULL.

str[0]=='\0' tells you if the string is of zero-length.

In that code, the test:

if ((str == NULL) || (str[0] == '\0'))

is used to catch the case where it is either NULL or has zero-length.


Note that short-circuiting plays a key role here: The point of the test is to make sure that str is a valid c-string with length at least 1.

  • The second test str[0] == '\0' will only work if str is not NULL.
  • Therefore, the first test str == NULL is needed to break out early when str is NULL.