English Deutsch Français Italiano Español Português 繁體中文 Bahasa Indonesia Tiếng Việt ภาษาไทย
All categories

#include
main()
{
char i=0;
for(;i>=0;i++) ;
printf("%d\n",i);
}

if i compile this prgm i get result as -128
why??

2007-08-07 07:09:37 · 4 answers · asked by Anonymous in Computers & Internet Programming & Design

4 answers

Arithmetic overflow. Signed chars go from -128 to 127. The char type having only one byte, it can only hold 256 values, and with one of the bits used for the sign of the number, only 7 bits remain:
so it goes from 0 to 127, and then from -128 to -1. The first number in this type to be negative is -128.

2007-08-07 07:15:00 · answer #1 · answered by napoleon9th 4 · 2 0

I am not sure in what level you are; so, I am sorry if my answer looks too simple.

integral data types like char and int work somehow like the time in clock. After they reach the maximum, they would start from the beginning. So, for signed char data type, -128 is next after +127, and for unsigned char, 0 is again after 255. Your variable, i, goes from 0 to +127 because they are all positive. Then it is reset to -128 where it is not positive any more, and the loop terminates.

You sure know that a char as an integer data type is safe for quantities which are in the range 0 <= char <= 127. Some compilers treat char as signed while others treat it as unsigned. Therefore, normally you would use a char integral data type when you are sure that your data would not exceed it limits.

2007-08-07 14:28:42 · answer #2 · answered by ʃοχειλ 7 · 0 0

Because... you use the wrong type for the variable, and C++ let's you do dumb things like that.

A "char" is basically 1 byte.

You assign a byte to be 0, but not the ASCII "0", but the value of 0. So if you keep adding to it, the byte, which has up to 256 values, overflowed, when you added 1 to 127, the max possible vallue for smallint, and became -128. That got you out of the loop as it is no longer >= 0

There used to be a joke that C allows you to shoot your own foot, while C++ allows you to blow your whole leg off. This example should illustrate the point quite clearly.

2007-08-07 14:28:56 · answer #3 · answered by Kasey C 7 · 0 0

Maybe becuase you're using a char, and the way that is written, I'd expect an infinite loop.

2007-08-07 14:19:23 · answer #4 · answered by Yahoo! Answerer 6 · 1 2

fedest.com, questions and answers