C++ Goto variable
C++ Goto variable
是否有一种方法可以在标签名称的位置使用变量调用goto语句?
我正在寻找类似的东西(这对我不起作用):
// std::string or some other type that could represent a label
void callVariable(std::string name){
goto name;
}
int main(){
first:
std::cout << "Hi";
callVariable(first);
return 0;
}
我不是真的在用这个,我对学习更感兴趣。
是,不是。没有这样的标准语言特性,但它至少在GCC中是一个编译器扩展:
int main() {
void* label;
first:
std::cout << "Hi";
label = &&first;
goto *label;
}
这就是说,我必须努力思考一个用例,它比任何标准替代方案都好。
你问:
”是否有一种方法可以在标签名称的位置使用变量调用goto语句?
是的,c++中提供这种效果的特性叫做switch
。从句法上讲,它不涉及goto
这个词。但是它跳转到由变量指定的标签,因此,使用它可以模拟各种基于goto
的脏代码,包括早期Basic的on ... goto ...
。
你假设的例子
int main(){
first:
std::cout << "Hi";
callVariable(first);
return 0;
}
白马王子;在真实的c++中是这样的:
#define CALL_VARIABLE( where ) next_jump = where; break;
auto main()
-> int
{
enum Label {first, second, third};
Label next_jump = first;
for( ;; ) switch( next_jump )
{
case first:
std::cout << "Hi";
CALL_VARIABLE( first );
}
}
简短的回答:no.
长话短说:没有。你为什么想要这个?别再用goto
了。
也许(只是猜测)你想要的是一个std::function
或switch
代替…
这是一个简单的宏解决方案:
#define CALL_VARIALBLE(name) goto name;
int main(){
first:
std::cout << "Hi";
CALL_VARIALBLE(first);
return 0;
}
动态位置不能goto
但是你可以看看POSIX setjmp
/longjmp
,它可以用来跳转到应用程序中预定义的位置。MSVC也支持。
#include <stdio.h>
#include <setjmp.h>
static jmp_buf buf;
void second(void) {
printf("secondn"); // prints
longjmp(buf,1); // jumps back to where setjmp was called - making setjmp now return 1
}
void first(void) {
second();
printf("firstn"); // does not print
}
int main() {
if (!setjmp(buf))
first(); // when executed, setjmp returned 0
else // when longjmp jumps back, setjmp returns 1
printf("mainn"); // prints
return 0;
}
相关文章:
- C++ Singleton - Prevent ::instance() to variable
- 在 ubuntu3 上C++ goto 定义有什么解决方案吗16.04?
- 如何正确指定 goto 语句的标签?
- 如何通过多类"Union variable" (sfml) 使用轮询事件
- ANTLR GOTO statement
- 为什么我的功能在使用 goto 时会给我带来"expected primary-expression before '}' token"?
- 将成员函数作为构造函数参数调用时出错 "Variable is not a type name"
- 为什么我会收到"Run-Time Check Failure #2 - Stack around the variable 'pr' was corrupted"错误?
- C++:寻找"returning address of local variable..."的更正
- C++ - 在我尝试制作一个简单的计算器时有一个"uninitialized local variable y used"警告
- Visual Studio Code "variable " u8 的 C/C++ 扩展名 " " 不是类型名称"
- 如何在复杂的算法中处理goto函数?
- 使用 goto 语句C++块进行 python化
- C++ "Using Uninitialized Memory.. (variable name) "
- cudaMallocManaged for host-initiated variable
- Cppcheck "Reference to auto variable returned"失败的原因?
- 使用flag、return、exception、goto或break中止过程
- OpenCV 和 C++:"Can't resolve variable 'Mat`"
- 是否有用于"go to variable type definition" C++中"auto"变量的 Visual Studio 键盘快捷方式?
- C++ Goto variable