C++ integer overflow

前端 未结 4 1386
小蘑菇
小蘑菇 2020-12-10 20:54

I\'m just starting to teach myself C++, and have begun learning about integer overflow. Out of curiosity I wrote some tests just to see what occurs with certain integer valu

4条回答
  •  悲哀的现实
    2020-12-10 21:44

    Integer comes in two types. Signed and unsigned, both 32bits traditionally.

    In first case you are using signed Integer. In this case, 1 bit is reserved for sign and rest of 31 are for magnitude. In this case, biggest number that can be saved is 2^31 - 1 = 2147483647. Adding one to it will affect most significant bit, changing number to negative. (Google 2's complement notation of numbers for more details).

    In 2nd case, you are using unsigned int in which all 32bits are reserved for magnitude. Hence biggest number that be stored is 2^32 - 1. Adding one to it will make zero. E. G. Say we have 3 bit number system, 111 = 7. Adding one to it will make it 1000, but since its 3bit system, it will become 000 = 0

提交回复
热议问题