Kaustubh Shankar
Kaustubh Shankar

Reputation: 21

Why does this program lead to an infinite loop?

I tried the follow program,

#include<stdio.h>

int main(void)
{
    char ch;

    for(ch='(';ch<='x';ch+='(')
    {
        printf("%c\n",ch);
    }

    return 0;
}

I expected the program to give the following output,

(
P
x

(ASCII value of '(' is 40, 'P' is 80, 'x' is 120)

But the program generated an infinite loop instead.

Then I tried another program,

#include<stdio.h>

int main(void)
{
    char ch;

    for(ch='(';ch<'x';ch+='(')
    {
        printf("%c\n",ch);
    }

    return 0;
}

This time the output was,

(
P

So I am not able to understand why the,

ch<='x'

in the first program resulting in a infinite loop.

Upvotes: 0

Views: 84

Answers (1)

user2736738
user2736738

Reputation: 30926

By the description we can say that char is signed in your system (max value of 127 - SCHAR_MAX). And when you were adding '(' to it, you are adding 40 with 120 (results in 160 which is greater than 127)and results in implementation defined behavior. (In your case supposedly it gets a value smaller than 'x' that's why the loop doesn't stop - But this is something you can't rely on - *this is implemenation defined behavior).

Also you asked in comment - why doesn't it stop at 120 (in first case)? First of all, your condition is <='x' so the value would be incremented when it is equal to the value 'x'.

Edit: Also one thing - this is not undefined behavior in that - char is promoted to int and then result is converted to char. This conversion is implementation defined behavior.(There are no arithmetic operations on integer types narrower than int that's why the integer promotions are done) [Noted by: Keith Thompson]

Upvotes: 2

Related Questions