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.
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.
str[0] == '\0'
will only work if str
is not NULL.str == NULL
is needed to break out early when str
is NULL.