Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is character array processed as true by if statement?

Tags:

c++

c

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");
}
like image 751
Aryav Bhola Avatar asked Sep 08 '25 03:09

Aryav Bhola


1 Answers

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.

like image 74
Sam Varshavchik Avatar answered Sep 10 '25 01:09

Sam Varshavchik