Pelles C forum

C language => Beginner questions => Topic started by: gho on April 12, 2017, 08:50:46 AM

Title: for loop issue
Post by: gho 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)]);
}

Title: Re: for loop issue
Post by: frankie 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 (http://forum.pellesc.de/index.php?topic=6663.0).

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 (http://stackoverflow.com/questions/7221409/is-unsigned-integer-subtraction-defined-behavior) (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...  :(
Title: Re: for loop issue
Post by: TimoVJL 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.