C# 中的算术异常
为什么在 C# 中示例 A 有效、可编译并且只会换行,而示例 B 则无法编译?
A
int val = 0;
val = val + Int32.MaxValue +2;
或
int val = Int32.MaxValue;
val++;
B
int val = 0;
val = 2147483647 + 1;
或
int val = 0;
int val = Int32.MaxValue + 1;
我知道默认情况下不会检查算术异常,除非您在配置中使用已检查的方法、块或属性明确执行此操作。我的问题更多地与编译器有关,而不是算术异常如何发生。
Why in C# is Example A valid, compilable and will just wrap while examples B will not compile?
A
int val = 0;
val = val + Int32.MaxValue +2;
or
int val = Int32.MaxValue;
val++;
B
int val = 0;
val = 2147483647 + 1;
or
int val = 0;
int val = Int32.MaxValue + 1;
I know by default that arithmetic exceptions are not checked by default unless you explicitly do so using checked method, block or attribute in the config. My question relates more to compiler then how an arithmetic exception happens.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
它只是与编译时检查的限制有关。有些事情只能在运行时才能知道。
It simply has to do with the limitations of the compile time checking. Certain things can only be known at runtime.
您不知道,因为该语句不正确。事实上,你知道它是不正确的,因为你提供了一个案例,证明你的陈述是错误的!
我建议您参阅 C# 规范的第 7.6.12 节,为了您的方便,我在此处复制了其中的一部分:
请参阅规格了解更多详细信息。
You do not know that because that statement is incorrect. And in fact you know it to be incorrect because you've provided a case where your statement is proven false!
I refer you to section 7.6.12 of the C# specification, a portion of which I reproduce here for your convenience:
See the spec for further details.
您的 B 示例在编译时是常量折叠,向编译器表明它肯定会溢出。
由于您的 A 示例使用变量,因此表达式无法(完全)常量折叠,因此编译器无法保证这些值会导致溢出。
例如...
但是,如果您知道
val
不会改变,并将 0 分配给const int
:您可以获得编译时溢出检查回来,因为该值可以完全确定,因此常量折叠。
Your B examples are constant-folded at compile time, indicating to the compiler that it's guaranteed to overflow.
Because your A examples use variables, the expressions cannot be (completely) constant-folded, so the compiler can't guarantee that the values will result in an overflow.
For instance...
However, if you know that
val
won't change, and assign 0 to aconst int
:You can get your compile-time overflow check back because the value can be completely determined and therefore constant-folded.