Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

151
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda