Reputation: 107
The range of the Long data type is -9223372036854775808
to 9223372036854775807
, but the following statement generates compiler error "BC30036: Overflow":
Dim a As Long = -9223372036854775808L
Why is this an error? How can I specify the constant -9223372036854775808
in code?
Upvotes: 9
Views: 990
Reputation: 55359
The compiler parses the expression -9223372036854775808L
as a unary minus operator applied to the decimal integer literal 9223372036854775808L
. According to the VB.NET specification:
A decimal integer literal is a string of decimal digits (0-9).
And:
If an integer literal's type is of insufficient size to hold the integer literal, a compile-time error results.
9223372036854775808L
is too large for a Long
, so you get an overflow error.
(The minus sign isn't part of the integer literal.)
To specify -9223372036854775808
literally, use a hexadecimal literal:
Dim a As Long = &H8000000000000000
The VB.NET specification alludes to this as well:
Decimal literals directly represent the decimal value of the integral literal, whereas octal and hexadecimal literals represent the binary value of the integer literal (thus, &H8000S is -32768, not an overflow error).
Of course, for clarity you should probably just use Long.MinValue
instead of a literal:
Dim a As Long = Long.MinValue
As René Vogt pointed out, the equivalent statement compiles fine in C#:
long a = -9223372036854775808L;
That's because (unlike VB.NET) C# supports this as a special case:
When a decimal_integer_literal with the value 9223372036854775808 (2^63) and no integer_type_suffix or the integer_type_suffix
L
orl
appears as the token immediately following a unary minus operator token, the result is a constant of typelong
with the value -9223372036854775808 (-2^63). In all other situations, such a decimal_integer_literal is of typeulong
.
Upvotes: 9