当`int`达到最大值并通过postfix ++进行测试时,代码是否定义明确? [英] When an `int` at max value and tested with with postfix ++, is code well-defined?

查看:74
本文介绍了当`int`达到最大值并通过postfix ++进行测试时,代码是否定义明确?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

示例未定义行为的一个示例是整数溢出时的行为. C11dr§3.4.33

EXAMPLE An example of undefined behavior is the behavior on integer overflow. C11dr §3.4.3 3

int溢出是未定义的行为,但这是否适用于存在循环的以下对象,并且不使用当前范围之外的i的副作用?特别是,后缀增量规范对您有帮助吗?

int overflow is undefined behavior, but does that apply to the following which exists the loop, and does not use the the side effect of the now out-of-scope i? In particular, does this Postfix increment spec help?

...结果的值计算先于的副作用进行排序 更新操作数的存储值. ...§6.5.2.42

... The value computation of the result is sequenced before the side effect of updating the stored value of the operand. ... §6.5.2.4 2

使用功能良好的C11进行编译而不会发出警告

Compiles without warnings with well-enabled C11

#include <limits.h>
#include <stdio.h>

int main(void) {
  // Specified behavior when `i` has the value `INT_MAX`?
  for (int i = INT_MAX - 2; i++ < INT_MAX;) {
    printf("%d\n", i);
  }
  puts("Done");
  return 0;
}

样本输出

2147483646
2147483647
Done

当然可以使用下面的方法重新编写代码以避免这种麻烦.尽管如此,仍在寻找有关上述内容的确认. (我认为是UB.)INT_MINi--也存在类似的问题.

Of course code can be re-written to avoid this quandary with the below. Still, looking for confirmation concerning the above. (I think it is UB.) A similar issue exists with INT_MIN and i--.

  for (int i = INT_MAX - 2; i < INT_MAX;) {
    i++; 
    printf("%d\n", i);
  }


GNU C11 (GCC) version 5.3.0 (i686-pc-cygwin)
    compiled by GNU C version 5.3.0, GMP version 6.1.0, MPFR version 3.1.4, MPC version 1.0.3
'-std=c11' '-O0' '-g3' '-Wpedantic' '-Wall' '-Wextra' '-Wconversion' '-c' '-fmessage-length=0' '-v' '-MMD' '-MP' '-MF' xx.o' '-o' 'xx.o' '-mtune=generic' '-march=i686'
/usr/lib/gcc/i686-pc-cygwin/5.3.0/cc1.exe -quiet -v -MMD xx.d -MF xx.d -MP -MT xx.o -dD -Dunix -idirafter   ... xx.c

推荐答案

无论范围i为何,当i为2147483647时,程序在i++评估中具有未定义的行为(假设您的INT_MAX = 2147483647)系统).

Regardless of the scope i, the program has undefined behaviour in the evaluaton of i++ when i is 2147483647 (assuming INT_MAX=2147483647 on your system).

您的示例可以重写为:

include <limits.h>

int main(void) {
  // Specified behavior when `i` has the value `INT_MAX`?
  {
      int i = INT_MAX;
      i++;
  }
  puts("Done");
  return 0;
}

i++的值计算会导致整数溢出,而与是否使用计算值无关,或者该对象是否在下一个序列点之后立即不复存在;对象的顺序点或存储持续时间与此处是否存在未定义的行为无关.

The value computation of i++ results in integer overflow irrespective of whether the computed value is used or if that object cease to exist right after the next sequence point; sequence point or storage duration of the object is irrelevant whether there's an undefined behaviour here.

这篇关于当`int`达到最大值并通过postfix ++进行测试时,代码是否定义明确?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆