gpt4 book ai didi

.net - "Overflow"编译器错误 -9223372036854775808L

转载 作者:行者123 更新时间:2023-12-04 07:32:08 25 4
gpt4 key购买 nike

Long data type 的范围是 -92233720368547758089223372036854775807 ,但以下语句会生成编译器错误“BC30036:溢出”:

Dim a As Long = -9223372036854775808L

Try it online!

为什么这是一个错误?如何指定常量 -9223372036854775808在代码中?

最佳答案

为什么这是一个错误?

编译器解析表达式 -9223372036854775808L作为应用于十进制整数文字 9223372036854775808L 的一元减运算符.根据VB.NET specification :

A decimal integer literal is a string of decimal digits (0-9).



和:

If an integer literal's type is of insufficient size to hold the integer literal, a compile-time error results.


9223372036854775808LLong 来说太大了,所以你会得到一个溢出错误。
(减号不是整数文字的一部分。)

如何在代码中指定常量 -9223372036854775808?

指定 -9223372036854775808从字面上看,使用十六进制文字:
Dim a As Long = &H8000000000000000

VB.NET 规范也提到了这一点:

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).



当然,为了清楚起见,您可能应该只使用 Long.MinValue而不是文字:
Dim a As Long = Long.MinValue

C#呢?

正如 René Vogt 指出的,等效语句在 C# 中编译得很好:
long a = -9223372036854775808L;

那是因为(与 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 or l appears as the token immediately following a unary minus operator token, the result is a constant of type long with the value -9223372036854775808 (-2^63). In all other situations, such a decimal_integer_literal is of type ulong.

关于.net - "Overflow"编译器错误 -9223372036854775808L,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49113815/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com