以下两个语句会导致编译器溢出错误(原因是常量表达式默认会检查溢出):
int i=(int)(int.MaxValue+100); // error
long l=(long)(int.MaxValue+100); // error
但是,如果编译器能够发现将两个值相加会导致溢出,为什么它不将 int.MaxValue
和 100
提升为 long
然后才尝试将它们加在一起?据我所知,这应该不是问题,因为根据下面的引述,整数文字也可以是 long
类型:
When an integer literal has no suffix, its type is the first of these types in which its value can be represented: int, uint, long, ulong.
谢谢
最佳答案
文字 100
可以表示为一个 int
,它是按顺序排列的这四种类型中的第一个,所以它是一个 int
>.
int.MaxValue
不是文字。它是 int
类型的公共(public)常量字段。
因此,加法运算是 int + int
,结果是 int
,然后在这种情况下会溢出。
要将文字 100
转换为 long
以便执行长整数加法,请在其后缀 L
:
long l = int.MaxValue + 100L;
关于c# - 而不是错误,为什么编译器不将这两个文字提升为 long 类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5667724/