當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


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()。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。