I was looking at an example and I saw this:
char *str;
/* ... */
if (!str || !*str) {
return str;
}
Does it mean it's empty or something?
I was looking at an example and I saw this:
char *str;
/* ... */
if (!str || !*str) {
return str;
}
Does it mean it's empty or something?
str
is a char pointer. !
negates it. Basically, !str
will evaluate to true (1) when str == NULL
.
The second part is saying, (if str
points to something) evaluate to true (1) if the first character is a null char ('\0'
) - meaning it's an empty string.
Note:
*str
dereferences the pointer and retrieves the first character. This is the same as doing str[0]
.
!str
means that there is no memory allocated to str
. !*str
means that str
points to an empty string.
Before asking you can do small tests.
#include <stdio.h>
int main()
{
char *str = "test";
printf("%d\n",*str);
printf("%c\n",*str); // str[0]
printf("%d\n",str);
if (!str || !*str)
{
printf("%s",str);
}
return 0;
}
meaning of !
is negation. Except 0
every value is true for if
condition. Here, str
and *str
return values that are not 0
. So, you can make an inference.
The first expression !str
evaluates true if str is set to NULL
, and false if set to anything else regardless of whether the memory pointed to is still allocated or not. This can lead to undefined behavior if str
is left set to memory that is no longer active.
The second expression !*str
evaluates true if the value at the address in str
is \0
(null character), but is not evaluated at all if !str
evaluated true due to the short-circuiting action of the boolean OR operator.