Best way to check if a character array is empty
Given this code:
char text[50];
if(strlen(text) == 0) {}
Followed by a question about this code:
memset(text, 0, sizeof(text));
if(strlen(text) == 0) {}
I smell confusion. Specifically, in this case:
char text[50];
if(strlen(text) == 0) {}
... the contents of text[]
will be uninitialized and undefined. Thus, strlen(text)
will return an undefined result.
The easiest/fastest way to ensure that a C string is initialized to the empty string is to simply set the first byte to 0.
char text[50];
text[0] = 0;
From then, both strlen(text)
and the very-fast-but-not-as-straightforward (text[0] == 0)
tests will both detect the empty string.
The second method would almost certainly be the fastest way to test whether a null-terminated string is empty, since it involves one read and one comparison. There's certainly nothing wrong with this approach in this case, so you may as well use it.
The third method doesn't check whether a character array is empty; it ensures that a character array is empty.
Depends on whether or not your array is holding a null-terminated string. If so, then
if(text[0] == '\0') {}
should be sufficient.
Edit: Another method would be...
if (strcmp(text, "") == 0)
which is potentially less efficient but clearly expresses your intent.
This will work to find if a character array is empty. It probably is also the fastest.
if(text[0] == '\0') {}
This will also be fast if the text
array is empty. If it contains characters it needs to count all the characters in it first.
if(strlen(text) == 0) {}