c++ - 在变量定义之前转到 - 它的值会发生什么?

标签 c++ goto local-variables register-allocation

这是我想知道的一些问题。给定下面的代码,我们能确定它的输出吗?

void f() {
  int i = 0; 
  z: if(i == 1) goto x; else goto u; 
  int a; 
  x: if(a == 10) goto y; 
  u: a = 10; i = 1; goto z; 
  y: std::cout << "finished: " << a; 
}

这是否保证根据 C++ 标准输出 finished: 10?或者编译器可以在gotoa之前的位置时占用a存放的寄存器吗?

最佳答案

注意:首先阅读对此的评论。约翰内斯或多或少地用一句恰如其分的标准引语否定了我的整个论点。 ;-)


我没有可用的 C++ 标准,所以我必须从 C 标准推断。

令人惊讶的是(对我来说),第 6.2.1 章 标识符的范围 没有说明从声明点开始的标识符的范围(正如我猜想的那样)。在您的示例中,int a 具有 block 范围,它“在关联 block 的末尾终止”,这就是关于它的全部内容。第 6.8.6.1 章 goto 语句 说“goto 语句不应从具有可变修改类型的标识符的范围之外跳转到该标识符的范围内” - 但由于您的 gotos 只在 within block 中跳转(因此,int a 的范围,似乎就 ISO/IEC 9899:1999 而言。

非常对此感到惊讶......

编辑 #1: 快速谷歌后,我得到了 C++0x 最终草案。我认为相关的声明是这里(6.7 声明声明,突出显示我的):

It is possible to transfer into a block, but not in a way that bypasses declarations with initialization. A program that jumps from a point where a variable with automatic storage duration is not in scope to a point where it is in scope is ill-formed unless the variable has scalar type, class type with a trivial default constructor and a trivial destructor, a cv-qualified version of one of these types, or an array of one of the preceding types and is declared without an initializer.

我认为您的代码符合标准的标准。但屁股丑陋,请注意。 ;-)

编辑#2:阅读您关于由于向后跳转而可能破坏 int a 的评论,我发现了这一点(6.6 Jump statements,突出显示我的):

Transfer out of a loop, out of a block, or back past an initialized variable with automatic storage duration involves the destruction of objects with automatic storage duration that are in scope at the point transferred from but not at the point transferred to.

一,int a 没有被“初始化”,如果我正确理解标准术语,它也不是对象。

关于c++ - 在变量定义之前转到 - 它的值会发生什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6791215/

相关文章:

c - 为什么2个不同的字符串在C中具有相同的地址?

php - 在 PHP 中将局部变量设置为 null

c++ - 如何从 C++ 文件中读取数字?

java - 有没有办法转到方法的特定部分,而不是方法的开始?

java - Java 中 goto 语句的替代方案

c++ - 多个返回语句或 "goto end;"

java - 使用 ASM4 重新映射标签

c++ - Qt Creator 中的代码传输

c++ - 记录代码头和源代码

c++ - 制作 : nothing can be done for 'all' error