Reputation: 13
In Turbo C++ (for C language) the limit of constant values is -32768 to 32767.
But if I am initializing the value more than 32767 or less than -32768 it is showing result.
So how does the compiler gives evaluates result for values more than 32767 and less than -32768.
How does the calculation takes place for these? To what does the extended value change?
Upvotes: 0
Views: 1308
Reputation: 214265
Lets say that you write something like int i = 40000;
on a 16 bit compiler. The compiler is smart enough to realize that the literal 40000
is actually too large to be an int, so the 40000
literal's type is therefore long
.
When you try to show a long into an int in C, the long get implicitly converted according to the following rules:
C11 6.3.1.3
1 When a value with integer type is converted to another integer type other than _Bool, if the value can be represented by the new type, it is unchanged.
2 Otherwise, if the new type is unsigned, the value is converted by repeatedly adding or subtracting one more than the maximum value that can be represented in the new type until the value is in the range of the new type.
3 Otherwise, the new type is signed and the value cannot be represented in it; either the result is implementation-defined or an implementation-defined signal is raised.
3) is what applies to int
, since int
is signed. Implementation-defined means that different compiler can implement it in different ways. Your compiler must document how this is done.
In practice though, your compiler & CPU use two's complement. So what will happen is that the number 40000
, which equals 0x9C40
on a binary level, simply gets treated as a signed 16 bit int. And according to two's complement, 0x9C40
for a signed 16 gives -25536
.
Upvotes: 1
Reputation: 8844
Turbo C++ is a 16-bit compiler, so the constants are 16-bit integers (range -32768..+32767) by default.
You can add an L
suffix to declare 32-bit constants, and store them in longs, like this:
const long LARGE_CONSTANT = 100000L;
The range for 32-bit long integers is -2147483648..+2147483647.
If you omit the L
suffix or store a large constant as int
instead of long
, it will be truncated to 16 bits. That is,
const int LARGE_CONSTANT = 100000;
will then imply LARGE_CONSTANT = -31072
because -31072
is the (unique) integer x such that x mod 216 = 100000 mod 216.
Upvotes: 3