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
Try it online!
Why is this an error? How can I specify the constant -9223372036854775808
in code?
In general, a data type overflow error is when the data type used to store data was not large enough to hold the data. Furthermore, some data types can only store numbers up to a certain size. An overflow error will be produced, for example, if a data type is a single byte and the data to be stored is greater than 256.
The most-common cause of stack overflow is excessively deep or infinite recursion, in which a function calls itself so many times that the space needed to store the variables and information associated with each call is more than can fit on the stack. An example of infinite recursion in C.
It is important to point out that a stack overflow is a logical runtime error and not a syntax error. Syntax errors result when the computer cannot read a section of code correctly, and these errors are caught by the compiler or at other key points before production.
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With