I have a char array and I want to check if it is null.
if(_char_array[0] != '\0') {...}
is the same as
if(_char_array != '\0') {...}
thanks
I have a char array and I want to check if it is null.
if(_char_array[0] != '\0') {...}
is the same as
if(_char_array != '\0') {...}
thanks
 
    
     
    
    This if statement
if(_char_array[0] != '\0') {...}
checks whether a character array contains a non-empty string.
In fact there are compared two integers: the first character of the array  _char_array promoted to the type int and the integer character constant '\0' that has the type int.
The statement can be rewritten also like
if( _char_array[0] ) {...}
or
if( *_char_array ) {...}
This if statement
if(_char_array != '\0') {...}
does not make a sense because any array occupies a memory extent. So converted to a pointer to its first element it can not be a null pointer.
That is in this statement there are compared a pointer to the first element of the array due to the implicit conversion of the array to a pointer to its first element and a null pointer constant.
If _char_array is initially declared as a pointer then the above if statement checks whether the pointer is not a null pointer.
The statement can be rewritten like
if( _char_array ) {...}
 
    
    In the first if statement you were checking whether the first element of _char_array is 0 or not, whereas in the second if statement you were checking address of _char_array to be 0 or not.
If the address is 0 then there would be 2 cases:
char *_char_array = NULL;
char *_char_array = malloc(<any_size>); // but malloc failed and returned `NULL`
NOTE: Statically allocated arrays never have an address of 0.
 
    
    An array name is not a pointer, but an identifier for a variable of type array, which is implicitly converted to a pointer to the element type. These two are not the same at all, the array will always have value.
 
    
    While the syntax only differs by 3 characters, these do very different things once compiled.
if(_char_array[0] != '\0')This checks if the value at index 0 within _char_array is not equal to 0.
_char_array[0]char(_char_array[0]) != '\0'bool; it is true when the char from step 1 is not equal to 0.if (...)bool from step 2 is true.if(_char_array != '\0')This checks if _char_array is not equal to 0.
_char_arraychar* instead of char[], in which case it is equivalent to != 0 or != NULL since '\0' is the char literal for 0.(_char_array) != '\0'bool that is true when the entire char array from step 1 is not equal to 0.bool from step 2.To echo Jonathan Leffler's comment, don't get in the habit of starting names in C or C++ with a leading underscore _.
They're reserved by the standard so doing this is usually considered undefined behaviour, as it can cause namespace collisions if you try to use a different compiler, or even a different version of the same compiler.
