-
M4L53 • 3 年前 1
这锅编译器可不背,在C语言标准草案n2596(我常用的草案,我猜测应该几乎每一版标准都有)中6.5第5条中就明确指出“If an exceptional condition occurs during the evaluation of an expression (that is, if the result is not mathematically defined or not in the range of representable values for its type), the behavior is undefined.”。这属于未定义行为,基本上编译器怎么实现都行,特别是涉及到优化的时候。(但是无符号整数是“特例”(其实就是不算溢出),在6.2.5中第9条"The range of nonnegative values of a signed integer type is a subrange of the corresponding unsigned integer type, and the representation of the same value in each type is the same.44) A computation involving unsigned operands can never overflow, because a result that cannot be represented by the resulting unsigned integer type is reduced modulo the number that is one greater than the largest value that can be represented by the resulting type.")
比如说常见错误
(++a) = f(++a, ++a)
,这玩意应该是熟知的未定义行为,就不能期望某个特定的结果,和这个问题程序差不多。比如做优化的时候
if(a > 0 && b > 0){ if(a + b > 0){ // anything ... } else { // it is valid for this branch to be optimized out. } }
编译器有理由但不一定会优化掉第二个分支。
-
糖醋鱼 (tangcuyu) • 3 年前
墨佬说笑了 见笑了
-
-
-
艾恩凝(Nick) (aeneag) • 3 年前
以8位二进制表示 值的大小在[-128,127],至于为什么是-128到127 ,自行百度
这里的最小值就是 -128 ,它的补码是 1000 0000 再减去1 就是加上 -1 ,-1 的原码是10000001
补码就是1111 1111
1000 0000 +1111 1111 = 0111 1111 结果是补码
第一位是标志位,所有 原码也是 0111 1111 所以
int_min -1 = int_max
1 回复 0 0 0 -
糖醋鱼 (tangcuyu) • 3 年前
你这道理我都懂、但是为什么
INT_MIN-1 < 0 //这个表达式成立?
这个时候、他应该已经溢出了吧、难道C语言直接比较有什么特殊的机制?
1 回复 0 0 0 -
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
M4L53 • 3 年前
这锅编译器可不背,在C语言标准草案n2596(我常用的草案,我猜测应该几乎每一版标准都有)中6.5第5条中就明确指出“If an exceptional condition occurs during the evaluation of an expression (that is, if the result is not mathematically defined or not in the range of representable values for its type), the behavior is undefined.”。这属于未定义行为,基本上编译器怎么实现都行,特别是涉及到优化的时候。(但是无符号整数是“特例”(其实就是不算溢出),在6.2.5中第9条"The range of nonnegative values of a signed integer type is a subrange of the corresponding unsigned integer type, and the representation of the same value in each type is the same.44) A computation involving unsigned operands can never overflow, because a result that cannot be represented by the resulting unsigned integer type is reduced modulo the number that is one greater than the largest value that can be represented by the resulting type.")
比如说常见错误
(++a) = f(++a, ++a)
,这玩意应该是熟知的未定义行为,就不能期望某个特定的结果,和这个问题程序差不多。比如做优化的时候
if(a > 0 && b > 0){ if(a + b > 0){ // anything ... } else { // it is valid for this branch to be optimized out. } }
编译器有理由但不一定会优化掉第二个分支。
2 回复 1 2 0 -
-
就是编译器的原因,我用了两个在线编译器,一个出来0 一个出来1