Travis said:
I am using a function that returns a const char * that is usually a
word, etc. How can I check to see if what it returns is empty?
I tried if (function() == "")
"" evaluates to a string literal which is converted
to a pointer to that literal (iow it's a (non-NULL)
address). This pointer value will always be different
from the string you return (unless you're returning
the literal "", which means it *might* have the same
value).
and (function() == NULL) and (function()
The boolean value of NULL is false, but if you're returning
the address of a string (emtpy or not), it will have a non-NULL
address, thus a boolean value of true.
It's not valid to compare a pointer value with a character
value. Did your compiler give a warning? Anyway, here
you're again comparing the address of the string with
something, not determining if it's empty or not.
But then I see that the those if statements are flagging true when the
function returns back a char * or no length
A C-style string ends with a zero-value (null) character.
An empty string has no characters before this null. To
determine emptiness, check the first character.
if (*function())
; /* not empty, contains at least one character */
else
; /* string is empty (zero length) */
But if there's any chance that function() could return
NULL, then the expression *function() will give
undefined behavior. So check first:
char *p = function();
if(p && !*p) /* "if p is not NULL and string is empty..."
{
; /* etc */
}
-Mike