Best way to check if a character array is empty

ZPS picture ZPS · Nov 25, 2009 · Viewed 221.3k times · Source

Which is the most reliable way to check if a character array is empty?

char text[50];

if(strlen(text) == 0) {}

or

if(text[0] == '\0') {}

or do i need to do

 memset(text, 0, sizeof(text));
 if(strlen(text) == 0) {}

Whats the most efficient way to go about this?

Answer

bbum picture bbum · Nov 25, 2009

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.