-2
/*how will the value of i be changed in output*/

void main()
{
    int i = 150;
    char c = i;
    i = c;
    printf("%d", i);
}
Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278

1 Answers1

0

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.

Stephen Docy
  • 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
  • 1
    There'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