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?
The answer is: (char)0. Default values for primitives are 0, 0.0f, 0.0 (double), (char)0 and false (for boolean).
Check the pointer for NULL and then using strlen to see if it returns 0 . NULL check is important because passing NULL pointer to strlen invokes an Undefined Behavior. Save this answer.
// Pre: char array must have null character at the end of data. Thus, we first find out how long the data is. The variable length will be the index of the first null character in the array, which is also the length of the data.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With