读书人

setjmp()返回值有关问题

发布时间: 2012-02-08 19:52:21 作者: rapoo

setjmp()返回值问题
#include <iostream.h>
#include <setjmp.h>

//using namespace std;

class rainbow
{
public:
rainbow()
{
cout < < "rainbow() " < <endl;
}
~rainbow()
{
cout < < "~rainbow() " < <endl;
}
};

jmp_buf kansas;

void OZ()
{
rainbow RB;
int i = 0;
for(i;i < 3;i++)
{
cout < < "there 's no place like home " < <endl;
}
longjmp(kansas,47);
}
int main()
{
if(setjmp(kansas) == 0)
{
cout < < "tornado ,witch,munchkins...\n ";
OZ();
}
else
{
cout < < "Auntie Em " < < "i had the strongest dream " < <endl;
}
system( "PAUSE ");
return 0;
}

问题1:我在DEV++中,用using namespace std;居然编译不通过,为何?

问题2:执行结果是:
tornado ,witch,munchkins...
rainbow()
there 's no place like home
there 's no place like home
there 's no place like home
Auntie Em i had the strongest dream

在OZ()中调用longjmp后,应该是跳转到if(setjmp(kansas) == 0)这里了,这时候为何执行了else,难道setjmp(kansas)此时返回值不等于0?那应该等于多少?


[解决办法]
问题1
#include <iostream.h>
改为
#include <iostream>

问题2
longjmp(kansas,47) 跳转到if(setjmp(kansas) == 0) 并且 setjmp(kansas) 返回 47, 也就是longjmp 的第二个参数!
[解决办法]
问题1: VS2005 下没有这个问题. 可以正常运行.
问题2: 如果setjmp返回一个调用longjmp的结果, 它返回longjmp的value自变量. 因此这里返回47, 你可以用下面的程序测试一下:
#include <iostream>
#include <setjmp.h>

using namespace std; // VS2005 编译通过!

class rainbow
{
public:
rainbow()
{
cout < < "rainbow() " < <endl;
}


~rainbow()
{
cout < < "~rainbow() " < <endl;
}
};

jmp_buf kansas;

void OZ()
{
rainbow RB;
int i = 0;
for(i;i < 3;i++)
{
cout < < "there 's no place like home " < <endl;
}
longjmp(kansas,47);
}
int main()
{
int x;
if((x=setjmp(kansas)) == 0)
{
cout < < "tornado ,witch,munchkins...\n ";
OZ();
}
else if (x==47) // 这里运行结果和原来一样, 说明 返回了 47
{
cout < < "Auntie Em " < < "i had the strongest dream " < <endl;
}
system( "PAUSE ");
return 0;
}
[解决办法]
using namespace std; 请使用C++新的头文件格式,即不带 .h 的包含方式
[解决办法]
setjmp returns 0 after saving the stack environment. If setjmp returns as a result of a longjmp call, it returns the value argument of longjmp, or if the value argument of longjmp is 0, setjmp returns 1
----MSDN

读书人网 >C++

热点推荐