I tried the code given below and found that it actually prints "yes", which means that the character array is taken as true in if statement. But i wonder what is the reason. I mean its an array so did it returned the whole "string". Or it returned its first element that is "s", or it returned its memory location which is processed as true as anything other than 0 is true.
char a[] = "string";
if (a)
{
printf("yes");
}
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
.
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