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

163
Visualizações
for-loop condition ignored when comparing to negative integer

While writing a function to count in how many individual position the string sub appears in the string s i found that the for-loop didn't work when using the empty string as s.

char* s = "";
char* sub = "up";

for(int i = 0; i <= (strlen(s) - strlen(sub)); i++){

    //stuff
}

In this case the loop kept going as if the condition wasn't met.

However if i rewrite the condition this way it works as intended.

int max = strlen(s) - strlen(sub);

for(int i = 0; i <= max; i++){

   //stuff
}

So i was wondering what is it that could cause this kind of behaviour.

over 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

In the condition of the for loop

for(int i = 0; i <= (strlen(s) - strlen(sub)); i++){

    //stuff
}

the both expressions strlen( s ) and strlen( sub ) have the unsigned integer type size_t. So the expression strlen(s) - strlen(sub) also can not be negative.

As strlen( sub ) is greater than strlen( s ) then their difference will produce a very big value of the type size_t.

Try this call of printf

printf( "size_t( -2 ) = %zu\n", size_t( -2 ) );

Its output in some system can be for example the following

size_t( -2 ) = 4294967294

while the value if INT_MAX in the same system is equal to 2147483647.

Moreover as the value INT_MAX is less than the obtained value of the above expression then you can get an infinite for loop.

What you need is to rewrite the condition the following way

for ( size_t i = 0; i  + strlen( sub ) <= strlen(s); i++){

    //stuff
}
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