Why can't I directly set an __int64 variable to -2500000000?
Asked Answered
U

3

6

This program is written in VC++ 6.0 on a WindowsXP machine.

If I try to set an __int64 variable to -2500000000 directly, it is truncated to a 32bit value and the two's complement is taken.

__int64 testval;
testval = -2500000000;

At this point testval equals 1794967293 (110 1010 1111 1101 0000 0111 0000 0000 binary).

When I set the variable to 2500000000 and then multiply by negative one, it works:

__int64 testval;
testval = 2500000000;
testval *= -1;

The variable testval equals -2500000000 (1001 0101 0000 0010 1111 1001 0000 0000 binary).

Any ideas? Thanks.

Urbanism answered 18/2, 2011 at 20:53 Comment(1)
MSVC6? Ouch! That hurts!Disvalue
D
10

Get a newer compiler. VC6 standard compliance is VERY poor.

In VC6, try a suffix of i64, as in

__int64 toobig = -2500000000i64;

Found the documentation!

Daffi answered 18/2, 2011 at 21:5 Comment(4)
Thanks, that would be the preferred method, but it's not an option at the moment.Urbanism
@E: I think I have the solution for VC6, but I no longer have a copy installed where I can test it.Daffi
That works. Thanks! That needs to be linked in their documentation for __int64.Urbanism
@E: I agree, but I don't think Microsoft is fixing VC6 documentation anymore. That they still care whether it installs and runs on new versions of Windows is a miracle. And it seems to be on the old MSDN site which doesn't support community-contributed content, so I can't add it myself.Daffi
I
9

The compiler is treating the constant 2500000000 as a 32-bit number. You need to explicitly tell it to treat it as a long int by appending an LL to the end of the constant. So, try instead:

testval = -2500000000LL;

Update: Since your compiler doesn't support this, and you are stuck with VC6, try instead breaking it into a value that results from the product of two 32 bit numbers as in:

testval = -250000;
testval *= 10000;
Irrupt answered 18/2, 2011 at 20:58 Comment(5)
Probably safer to make it LL rather than LPlanarian
That (the compiler using a 32-bit type for that literal) is a violation of C++0x section [lex.icon]... anybody have the wording from C++03 or C++98?Daffi
C++03 probably isn't going to help much, considering Visual C++ 6 shipped in the late 90s.Hanfurd
Thanks,LL doesn't work, I get a compiler erro, and L makes no difference because a long in WindowsXP(32bit) is still only 32bits, the same as an int.Urbanism
I think it's preferable to split a whole thousand instead of a myriad, also it's much easier to count (grasp) three instead of four zero.Vibration
B
2

The correct syntax is -2500000000LL. If it doesn't work, get a newer compiler.

Beneficence answered 18/2, 2011 at 21:16 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.