NO

Author Topic: for loop issue  (Read 2606 times)

gho

  • Guest
for loop issue
« on: April 12, 2017, 08:50:46 AM »
This "for loop" doesn't work as expected (with version 7.0.350). Nothing is printed.
int main()
{
   char s[]="ABC";
   for(int i=strlen(s);i>=-strlen(s); i--)
      printf("%c",s[abs(i)]);
}


Offline frankie

  • Global Moderator
  • Member
  • *****
  • Posts: 2096
Re: for loop issue
« Reply #1 on: April 12, 2017, 10:09:53 AM »
Hello gho. Welcome on PellesC.
First of all please use current compiler version, 8.00.60, that you can download from here.

There is no bug in the compiler for the snippet you have posted.
It is your code indeed to be bugged.

The problem is that you are comparing a signed int, the loop variable i, with the unsigned size_t value returned from strlen.
The compiler try to apply integer promotion privileging the type that can contain bigger value, the usigned, but sign change (equivalent to arithmetiic computation 0-val) generates an underflow. And this lead to wrong value. See here (the concept is valid for overflow and underflow).
Casting the result from strlen solve the problem:
Code: [Select]
int main(void)
{
   char s[]="ABC";
   for(int i=strlen(s);i>=-((int)strlen(s)); i--)
      printf("%c",s[abs(i)]);
}
Of course on compilers not fully C99-C11 compliant it could eventually work...  :(
« Last Edit: April 13, 2017, 10:18:18 AM by frankie »
It is better to be hated for what you are than to be loved for what you are not. - Andre Gide

Offline TimoVJL

  • Global Moderator
  • Member
  • *****
  • Posts: 2091
Re: for loop issue
« Reply #2 on: April 13, 2017, 08:51:54 AM »
As PellesC is a C99 compiler, you have to add
Code: [Select]
int strlen(char *s);to get that example compiled without headers.
msvc don't need that (C89) as function without declaration defaults as return int.
« Last Edit: April 13, 2017, 09:28:19 AM by TimoVJL »
May the source be with you