mojtaba al moussawi mojtaba al moussawi - 1 year ago 67
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

variable is of type
which is usually unsigned.

My code:


#define SIZE 100

int main(){
char str[SIZE];
size_t i=0;
size_t j;
puts("Enter any string");



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 Source

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:


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.


  • you can use strlen()instead of looping over it yourself.
  • Check the return value of scanf() if input reading wad successful.
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download