为啥goto不能跳过初始化操作
为什么goto不能跳过初始化操作?
……
goto test;
int i;
string str;
test:
{
……
}
……
为什么这里通不过编译呢?把string str;这一句拿到goto之前就可以了?
为什么后面的int i;这一句不需要拿到goto之前呢?
------解决方案--------------------
依据我的判断应该是内存的事,函数和 int i;变量都是在栈上的,而且i所占内存大小是固定的,而string是动态内存分配,在堆上的,大小可变。
------解决方案--------------------
具体内部原因不知道,也待答案
1.在c++ Primer中倒是提到,goto 不能向前跳过变量定义语句,给出的理由是可能引起未定义的变量使用。当确实要这样使用时,需要把定义语句使用{}括起来。
但是奇怪在vs中,确实只需要注释 string 定义的一句就可以执行。
但是在g++中,定义i的同时赋值(int i=10;),则会提示出错,但是如果只声明i,在声明后赋值或者不赋值(int i; i=10),都不报错。
------解决方案--------------------
6.7 Declaration statement
.............A program that jumps from a point where a local variable with automatic storage duration is not in scope to a point where it is in scope is ill-formed unless the variable has POD type (3.9) and is declared without an initializer (8.5).
就是说,当跳过自动局部变量时,只能跳过未初始化的POD变量,其余情况都属于错误的代码结构。
……
goto test;
int i;
string str;
test:
{
……
}
……
为什么这里通不过编译呢?把string str;这一句拿到goto之前就可以了?
为什么后面的int i;这一句不需要拿到goto之前呢?
------解决方案--------------------
依据我的判断应该是内存的事,函数和 int i;变量都是在栈上的,而且i所占内存大小是固定的,而string是动态内存分配,在堆上的,大小可变。
------解决方案--------------------
具体内部原因不知道,也待答案
1.在c++ Primer中倒是提到,goto 不能向前跳过变量定义语句,给出的理由是可能引起未定义的变量使用。当确实要这样使用时,需要把定义语句使用{}括起来。
但是奇怪在vs中,确实只需要注释 string 定义的一句就可以执行。
但是在g++中,定义i的同时赋值(int i=10;),则会提示出错,但是如果只声明i,在声明后赋值或者不赋值(int i; i=10),都不报错。
------解决方案--------------------
6.7 Declaration statement
.............A program that jumps from a point where a local variable with automatic storage duration is not in scope to a point where it is in scope is ill-formed unless the variable has POD type (3.9) and is declared without an initializer (8.5).
就是说,当跳过自动局部变量时,只能跳过未初始化的POD变量,其余情况都属于错误的代码结构。