+ 4

In C++, why does the value turn negative when a very large stored variable is printed out?

*Please explain in simple language (Ive heard of integer overflow and unsigned integers but have no idea what it is) to an absolute beginner :) Much appreciated !

4th Sep 2018, 3:24 PM
Michael
Michael  - avatar
6 Answers
+ 5
Michael if you go out of range, it again starts with lower value.. for example, short int can store value between -32768 to 32767.. if you use any value between this range, it works fine... try with value as 32768 and it is one more than 32767... so, output will be lower range i.e. -32768 + 0 = -32768.. if you consider value 32769, it is two more than 32767.. so, output would be -32768+1 = -32767 check in code playground for other higher value using below snippet: short int a = 32800; cout << a;
4th Sep 2018, 3:30 PM
Ketan Lalcheta
Ketan Lalcheta - avatar
+ 2
AFAIK, it's a matter of number representation. Basically... you can store up to 2āæ different informations depending on the data type you're working with. Since we have to represent negative numbers too, the first half of the available numbers is used to represent positive numbers, the second half is used to represent the negative ones, so if you want to use a number greater than 2āæ-1 you're gonna visit the negative side, lol. Eg. Let's say `n = 3` so that you have a data type that can store up to 2Ā³ informations. 2Ā³ = 8, so the representation is gonna be something like: 0 1 2 3 -4 -3 -2 -1 input: 2 output: 2 input: 6 output: -3 (sixth position) OC, let me know if i said something wrong. Have a nice day!
4th Sep 2018, 5:20 PM
Maz
Maz - avatar
6th Sep 2018, 4:47 PM
Fajar Maftuh Fadli
Fajar Maftuh Fadli - avatar
+ 1
Ketan Lalcheta Thank you.
5th Sep 2018, 1:38 PM
Michael
Michael  - avatar
0
Think about numbers as it is a ring. When they overflow the storage they start from the beginning. Beginning of the signed integer is the lowest negative value. Integer type (int8_t, int16_t, ...) is just a size of the storage and the ring.
4th Sep 2018, 8:25 PM
Sergey Ushakov
Sergey Ushakov - avatar
- 1
cout ((( a 6
5th Sep 2018, 11:54 AM
Š¦Š¾Š³Š¾Š¾
Š¦Š¾Š³Š¾Š¾ - avatar