当前位置: 首页>>编程示例 >>用法及示例精选 >>正文


C++ feholdexcept()用法及代码示例

C++ 中的feholdexcept() 函数首先将当前浮点环境保存到一个 fenv_t 对象,然后清除所有浮点状态标志。

feholdexcept() 函数在<cfenv> 头文件中定义。

feholdexcept()原型

int feholdexcept( fenv_t* envp );

feholdexcept() 函数将当前浮点环境保存到 envp 指向的对象,正如 fegetenv() 所做的那样,并清除所有浮点状态标志。

最后,它安装了不间断模式,以便将来的浮点异常不会中断执行,直到通过调用 feupdateenv 或 fesetenv 恢复浮点环境。

参数:

  • envp:指向存储浮点环境状态的 fenv_t 类型对象的指针。

返回:

  • 成功时,feholdexcept() 函数返回 0。
  • 失败时,它返回非零。

示例:feholdexcept() 函数如何工作?

#include <iostream>
#include <cmath>
#include <cfenv>
#pragma STDC FENV_ACCESS ON
using namespace std;

void print_exceptions()
{
	cout << "Raised exceptions: ";
	if(fetestexcept(FE_ALL_EXCEPT))
	{
		if(fetestexcept(FE_DIVBYZERO))
			cout << "FE_DIVBYZERO ";
		if(fetestexcept(FE_INEXACT))
			cout << "FE_INEXACT ";
		if(fetestexcept(FE_INVALID))
			cout << "FE_INVALID ";
		if(fetestexcept(FE_OVERFLOW))
			cout << "FE_OVERFLOW ";
		if(fetestexcept(FE_UNDERFLOW))
			cout << "FE_UNDERFLOW ";
	}
	else
		cout << "None";

	cout << endl;
}

int main(void)
{
	fenv_t envp;

	/* raise certain exceptions */
	feraiseexcept(FE_INVALID|FE_DIVBYZERO);
	print_exceptions();
	
	/* saves and clears current exceptions */
	feholdexcept(&envp);
	print_exceptions();
	
	/* restores saved exceptions */
	feupdateenv(&envp);
	print_exceptions();

	return 0;
}

运行程序时,输出将是:

Raised exceptions: FE_DIVBYZERO FE_INVALID
Raised exceptions: None
Raised exceptions: FE_DIVBYZERO FE_INVALID

相关用法


注:本文由纯净天空筛选整理自 C++ feholdexcept()。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。