Pawan Joshi
Pawan Joshi

Reputation: 1579

why this loop is running infinite times in c?

I was just experimenting a code in C programming. and came to know a strange behavior. Well... Since i am not an expert on C, so i don't know whether its strange or normal.

Basically my question is all about the difference between the following two lines of code:-

char a = 'h'; // here variable a is not an array of "char"

and

char a = 'hi'; //here variable a is not an array of "char" as well (i don't know if compiler assumes it as an array or not but , at least i didn't declared it that way )

I used the following codes

first:-

char a =0;
for(;a<'hi';a++)
{
    printf("%d= hello world \n",a);
}

second:-

char a;
for(a='h';a<'hi';a++)
{
    printf("%d= hello world \n",a);
}

both of the above mentioned loops keep running forever,

Can somebody tell me why so ?

I might be missing a very basic concept of programing. please help me guys

Upvotes: 5

Views: 339

Answers (2)

bitmask
bitmask

Reputation: 34628

In C (as opposed to C++, as cited in some comments), character literals, always have type int. It doesn't matter if it's an ordinary one-character literal, such as 'c', or a multi-character literal, such as 'hi'. It always has type int, which is required to hold at least 16 bit. A char holds exactly one byte.

When comparing integer values of different type, integer-promotion rules kick in and the integer value of smaller size gets promoted to the larger one. That is why a < 'hi' can only be 1 ("true"). Even if promoted to type int, the variable a can never hold anything larger than MAX_CHAR. But the multi-character literal 'hi' is an int with a larger value than that in your complier's implementation.

The reason that a < m can succeed is that when declaring m, you initialise it with 'hi' which gets converted to type char, which indeed has a chance to compare not-less-than an other char.

Upvotes: 1

myaut
myaut

Reputation: 11504

That is because 'hi' has type int not a char. It also resolves to value 26729. But loop variable most likely (assuming char is 1-byte type and byte has 8 bits) is limited by 127 and after that overflows.

Note that this:

char a =0;
char m = 'hi';
for(; a < m; a++)
{
    printf("%d= hello world \n",a);
}

will work because 'hi' is will be coerced to char (105).

'hi' is a multi-character literal. It is not common practice in programming, it is "less known" C feature which became part of C99 standard. More information about them: http://zipcon.net/~swhite/docs/computers/languages/c_multi-char_const.html

Upvotes: 10

Related Questions