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

162
Views
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 answers
Answer question

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 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!