我想使用longjmp来模拟goto指令.我有一个包含struct类型元素的数组DS(int,float,bool,char).我想跳到标有"lablex"的地方,其中x是DS [TOP] .int_val.我怎么处理这个?
示例代码:
...
jmp_buf *bfj;
...
stringstream s;s<<"label"<<DS[TOP].int_val;
bfj = (jmp_buf *) s.str();
longjmp(*bfj,1);
Run Code Online (Sandbox Code Playgroud)
但是我认为它有问题我该怎么办?
错误:
output.cpp:在函数'int main()'中:
output.cpp:101:错误:从类型'std :: basic_string,std :: allocator>'转换为无效的类型'__jmp_buf_tag(*)[1]'
你可能根本不想使用longjmp,但是当人们回答"你为什么要这样做?"的问题时我讨厌它.正如已经指出你的longjmp()用法是错误的.这是一个如何正确使用它的简单示例:
#include <setjmp.h>
#include <iostream>
using namespace std;
jmp_buf jumpBuffer; // Declared globally but could also be in a class.
void a(int count) {
// . . .
cout << "In a(" << count << ") before jump" << endl;
// Calling longjmp() here is OK because it is above setjmp() on the call
// stack.
longjmp(jumpBuffer, count); // setjump() will return count
// . . .
}
void b() {
int count = 0;
cout << "Setting jump point" << endl;
if (setjmp(jumpBuffer) == 9) return;
cout << "After jump point" << endl;
a(count++); // This will loop 10 times.
}
int main(int argc, char *argv[]) {
b();
// Note: You cannot call longjmp() here because it is below the setjmp() call
// on the call stack.
return 0;
}
Run Code Online (Sandbox Code Playgroud)
您使用longjmp()的问题如下:
但实际上,你根本不可能使用longjmp().