Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

136
Views
Why is character array processed as true by if statement?

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");
}
over 4 years ago · Santiago Trujillo
3 answers
Answer question

0

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.

over 4 years ago · Santiago Trujillo Report

0

"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.

over 4 years ago · Santiago Trujillo Report

0

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.

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!