Home > Software engineering >  Infinite while loop when declaring a char variable with integer value
Infinite while loop when declaring a char variable with integer value

Time:03-16

The code works fine if I declare j as int but it goes into infinite loop when I declare it as char.

char j=1;
while (j<=255){
    printf("%d ",j);
    j =1;
}

CodePudding user response:

Tip: enable all warnings @Nate Eldredge to save time and receive a warning like:

warning: comparison is always true due to limited range of data type [-Wtype-limits]

Integer types in C have a limed range.

char has the same range as signed char or unsigned char, depending on the implementations uses signed or unsigned char.

Commonly CHAR_MAX, SCHAR_MAX, UCHAR_MAX are all 255 or less*1. So comparing a char <= 255 is always expected to be true.

char j=1;
while (j<=255){
  // Do something with j
}

Advanced

As code iterates, it does j =1; which is like j = j 1;. Eventually this attempts to assign a value to j which is more than CHAR_MAX. Assigning to an integer type a value outside its range leads to "either the result is implementation-defined or an implementation-defined signal is raised". Commonly, the result is a "wrapped value" or j increments as 126, 127, -128, -127, ...

With int j, the range of an int is much larger and that wrap does not occur before the loop ends. j<=255 eventually becomes false, ending the loop.


*1 Rare machines with more than 8-bits per char have greater range.

CodePudding user response:

As indicated in this URL, a char only have one byte and hence, the value is between 0 and 255. If you add 1 to 255 (for a char), you just get 0 again. So your condition j<=255 will always be met.

In case the meaning is that the range is between -128 and 127, then 127 1 gets calculated as -128.

  •  Tags:  
  • c
  • Related