/*how will the value of i be changed in output*/
void main()
{
int i = 150;
char c = i;
i = c;
printf("%d", i);
}

- 730,956
- 141
- 904
- 1,278

- 15
- 3
-
how the value of i will be change..? – rahul chaudhary Apr 01 '18 at 07:12
-
Edit the Question rather than leave comments that have additional questions or information. See [ask]. Also edit your question to ensure correct use of tags, and an example of the output your are seeing would be helpful for others trying to answer your question. – AJD Apr 01 '18 at 07:15
-
no duplicates? no time for diggin some ATM. – Jean-François Fabre Apr 01 '18 at 08:13
1 Answers
Because char
can only hold one byte of data, -128 to 127, so storing a value of 150 in it causes sign overflow, giving a negative result.
Sign overflow results in undefined behavior, however, what often happens is :
Up to the max positive value of 127, everything is ok.
When 128 is assigned, the sign bit gets set and the reported value flips to -128.
For every value of 1 you go above this value, the value will also increase.
So, in your case assigning 150, at 128 the bit flips, and you still have 22 left (150 - 128), so the final value could be -106 (-128 + 22).
And this is, in fact, the result I get on windows with Visual Studio if I try it. But again, this is undefined behavior, so there is no guarantee what you system will do when you overflow the sign bit.

- 4,738
- 7
- 18
- 31
-
and how the negative result can be calulated? or sign overflow work? – rahul chaudhary Apr 01 '18 at 07:30
-
The standard says that plain `char` has the same range as either `signed char` or `unsigned char` but is distinct from both. If the plain `char` type has the same range as `signed char`, the range mentioned is the normal range, but it need not be so. OTOH, the question would probably not be asked were it not so. – Jonathan Leffler Apr 01 '18 at 07:47
-
Thank you, I had noticed that `char` could be signed or unsigned, but couldn't find any other specific info related to that. – Stephen Docy Apr 01 '18 at 07:49
-
1There's no undefined behaviour here. *Out of range assignment* is not a case of overflow. Overflow is when the result of an *arithmetic operation* would exceed the bounds of the type of the result. Furthermore, some systems have `char` as 0-255, or a larger range even, in fact there are probably more such systems in existence than not. – M.M Apr 01 '18 at 08:09
-
See [C11 §6.2.5 Types ¶3-6](https://port70.net/~nsz/c/c11/n1570.html#6.2.5). See also [Sizes of integer types `
`](https://port70.net/~nsz/c/c11/n1570.html#5.2.4.2.1). See also [§6.2.6 Representations of types](https://port70.net/~nsz/c/c11/n1570.html#6.2.6) and [§6.2.6.2 Integer types](https://port70.net/~nsz/c/c11/n1570.html#6.2.6.2). – Jonathan Leffler Apr 01 '18 at 08:12