Why can I work with int> +32767?

I can read that int range (signed) from [-32767, +32767] but I can say for example

int a=70000; int b=71000; int c=a+b; printf("%i", c); return 0; 

And the result is 141000 (correct). Shouldn't the debugger tell me "this operation is out of range" or something like that?

I believe this should be with me, ignoring the basics of C programming, but not one of the books I'm reading now says anything about this "problem."

EDIT: 2147483647 seems to be an upper limit, thanks. If the sum exceeds this number, the result is negative, expected, but if it is a subtraction, for example: 2147483649-2147483647 = 2 , the result will still be good. I mean, why is the value 2147483649 true for this purpose (or at least it seems to me)?

+5
source share
7 answers

You misunderstood. The standard ensures that a int contains [-32767, +32767], but is allowed to hold more. (In particular, almost every compiler that you most likely use allows you to use the range [-2147483648, 2147483647]).

There is one more problem. If you assign the value assigned to a and b more, you probably won't get any warnings or errors. Integer overflow causes "undefined behavior", and literally everything is allowed.

+2
source

Range [-32767, +32767] is the required minimum range. Implementations are allowed to provide a larger range.

+6
source

In C ++, int has a length of at least 16 bits, but usually 32 bits on modern hardware. You can write INT_MIN and INT_MAX and test yourself.

Please note that signed integer overflow is undefined behavior , you are not guaranteed to receive a warning, except, possibly, high compiler warnings and debug mode.

+3
source

All types are compiler dependent. int used as the "native word" of the base equipment, which in 16-bit systems meant that int was 16 bits (which leads to a range from -32 to + 32 k). When 32-bit systems began to appear, then int naturally followed and became 32 bits, which can store values ​​from -2 to +2 billion.

However, this use of the "native word" for int did not follow when 64-bit systems appeared; I don’t know a 64-bit system or compiler with an int 64 bits.

See this link of integer types for more information.

+3
source

If int is four bytes, then unsigned is 4294967295, signed max. 2147483647 and signed by min. -2147483648

 unsigned int ui = ~0; int max = ui>>1; int min = ~max; int size = sizeof(max); 
+1
source

While the standard ensures that the int size must be 16 bits, it is usually implemented as a 32-bit value.

0
source

The size of the int (and the maximum value it can hold) depends on the compiler and the computer you are using. There is no guarantee that it will have 2 bytes or 4 bytes, but for C ++ variables there is a guaranteed minimum size.

You can see the list of minimum sizes for C ++ types on this page: http://www.cplusplus.com/doc/tutorial/variables/

0
source

Source: https://habr.com/ru/post/1240697/


All Articles