Why is character array processed as true by if statement?

Solution 1:

if (a)

In this context, a reference to an array decays to a pointer to the first value of the array. The same thing would happen if a were to get passed as a function parameter.

So, here, a is just a pointer. And since it's not a null pointer this always evaluates to true.

char a[6] = "string";

This is not really relevant, but this literal string has seven characters, not six, by the way. You forgot about the trailing \0.

Solution 2:

"string" is actually a const char[7] literal in C++ and a char[7] constant in C. Note that in C++, you cannot assign it to a char[6] as you must provide space for the NUL terminator. You can however omit it in C.

a decays to a pointer of type char*.

In either language, that pointer value cannot be 0 or implicitly convertible to false. So therefore the body of the if is run.

Solution 3:

In C-style arrays like char a[2] = "go"; the identifier of the array automatically decays into a pointer. And since a is pointing to a location in the memory (i.e. it's not NULL or 0) the condition of your if statement will always evaluate as true.

Solution 4:

From the C Standard (6.8.4.1 The if statement)

2 In both forms, the first substatement is executed if the expression compares unequal to 0. In the else form, the second substatement is executed if the expression compares equal to 0. If the first substatement is reached via a label, the second substatement is not executed.

and (6.3.2.1 Lvalues, arrays, and function designators)

3 Except when it is the operand of the sizeof operator or the unary & operator, or is a string literal used to initialize an array, an expression that has type ‘‘array of type’’ is converted to an expression with type ‘‘pointer to type’’ that points to the initial element of the array object and is not an lvalue. If the array object has register storage class, the behavior is undefined.

The declared array

char a[6] = "string";

occupies an extent of memory which address s not equal to 0.

So in this if statement

if (a)
{
    printf("yes");
}

the array is implicitly converted to a pointer to its first element. As the stored address in this pointer is not equal to 0 then the substatement of the if statement gets the control.