Namespaces
Variants

feholdexcept

From cppreference.net
< c ‎ | numeric ‎ | fenv
ヘッダーで定義 <fenv.h>
int feholdexcept ( fenv_t * envp ) ;
(C99以降)

まず、現在の浮動小数点環境を envp が指すオブジェクトに保存し( fegetenv と同様)、すべての浮動小数点ステータスフラグをクリアします。その後、非停止モードを設定します:浮動小数点環境が feupdateenv または fesetenv によって復元されるまで、将来の浮動小数点例外は実行を中断しません(トラップしません)。

この関数は、呼び出し元に対して発生させる可能性のある浮動小数点例外を隠す必要があるサブルーチンの開始時に使用できます。一部の例外のみを抑制し、他の例外を報告する必要がある場合、不要な例外をクリアした後、 feupdateenv の呼び出しによって非停止モードを終了するのが一般的です。

目次

パラメータ

envp - 浮動小数点環境が格納される fenv_t 型のオブジェクトへのポインタ

戻り値

0 成功時は0、それ以外の場合は非ゼロ。

#include <stdio.h>
#include <fenv.h>
#include <float.h>
#pragma STDC FENV_ACCESS ON
void show_fe_exceptions(void)
{
    printf("current exceptions raised: ");
    if(fetestexcept(FE_DIVBYZERO))     printf(" FE_DIVBYZERO");
    if(fetestexcept(FE_INEXACT))       printf(" FE_INEXACT");
    if(fetestexcept(FE_INVALID))       printf(" FE_INVALID");
    if(fetestexcept(FE_OVERFLOW))      printf(" FE_OVERFLOW");
    if(fetestexcept(FE_UNDERFLOW))     printf(" FE_UNDERFLOW");
    if(fetestexcept(FE_ALL_EXCEPT)==0) printf(" none");
    printf("\n");
}
double x2 (double x)   /* times two */
{
    fenv_t curr_excepts;
    /* Save and clear current f-p environment. */
    feholdexcept(&curr_excepts);
    /* Raise inexact and overflow exceptions. */
    printf("In x2():  x = %f\n", x=x*2.0);
    show_fe_exceptions();
    feclearexcept(FE_INEXACT);   /* hide inexact exception from caller */
    /* Merge caller's exceptions (FE_INVALID)        */
    /* with remaining x2's exceptions (FE_OVERFLOW). */
    feupdateenv(&curr_excepts);
    return x;
}
int main(void)
{    
    feclearexcept(FE_ALL_EXCEPT);
    feraiseexcept(FE_INVALID);   /* some computation with invalid argument */
    show_fe_exceptions();
    printf("x2(DBL_MAX) = %f\n", x2(DBL_MAX));
    show_fe_exceptions();
    return 0;
}

出力:

current exceptions raised:  FE_INVALID
In x2():  x = inf
current exceptions raised:  FE_INEXACT FE_OVERFLOW
x2(DBL_MAX) = inf
current exceptions raised:  FE_INVALID FE_OVERFLOW

参考文献

  • C11標準 (ISO/IEC 9899:2011):
  • 7.6.4.2 feholdexcept関数 (p: 213-214)
  • C99標準 (ISO/IEC 9899:1999):
  • 7.6.4.2 feholdexcept関数 (p: 194-195)

関連項目

浮動小数点環境を復元し、以前に発生した例外を発生させる
(関数)
現在の浮動小数点環境を保存または復元する
(関数)
デフォルト浮動小数点環境
(マクロ定数)
C++ドキュメント for feholdexcept