mojtaba al moussawi mojtaba al moussawi - 3 months ago 11
C Question

iterating an array backwards in For loop condition to stop at 0 when using unsigned integers causing infinite loop

I have a loop that has to go from j to 0 (inclusively). My

j
variable is of type
size_t
which is usually unsigned.

My code:

#include<stdio.h>
#include<conio.h>

#define SIZE 100

int main(){
char str[SIZE];
size_t i=0;
size_t j;
puts("Enter any string");
scanf("%s",str);
while(str[i]!='\0'){
i++;
}


for(j=i-1;j>=0;j--){

printf("%c",str[j]);
}


getch();
return 0;
}


I get an infinite loop. If I remove the equality of zero it outputs the reverse of string without the first letter. so what's the problem here?

Answer

size_t is an unsigned integer and it's never going to be less than 0. So the condition in for loop is always true:

for(j=i;j>=0;j--)

You can modify the condition to (a bit ugly though):

for(j=i; j-- > 0;){
   ...
}

Note that in your condition, you are printing the \0 null byte too, which is a non-printable character. (since the j starts with a value equal to the string length). The above condition takes care of that too.

Also:

  • you can use strlen()instead of looping over it yourself.
  • Check the return value of scanf() if input reading wad successful.