Humanity

Edit the world by your favorite way

volatileのこんな使い道

ちょっと前のcomp.std.c++メーリングリストから。

One use of volatile, that was not listed in the paper referred to above is
to prevent register allocation of particular variables.
Some computers, most notably the Intel Pentium series, use higher precision
for floating point numbers in registers than in memory. In some cases, when
EXACT CONSISTENT values are needed, variables for intermediate results can
be declared volatile to deliberately lose the excess precision.
The following function is NOT guaranteed to return true, even if the
arguments and their product have "reasonable" values.

bool test (double a, double b)
{
double c, d;
c = a * b;
d = a * b;
return ( c == d );
}

Making c and d volatile guarantees that they will have the same value, and
will compare equal, assuming that no out of range condition occurs.

適当だし間違ってるかもしれませんがとりあえず訳。
ところどころ分からないところがあったのでそこは原文のまま・・・

volatileの使い道のひとつで、上に挙がっていないものと言えば、変数をレジスタに割り当てることを防ぐことだ。
いくつかのcomputers, 特にIntel Pentiumシリーズはより精確な浮動小数点数を扱うためにメモリよりレジスタで扱おうとする。

また「正確でつじつまの合う(訳注:c == dがtrueになるような)」値が必要になった場合に中間的な結果のための変数(訳注:cやdのこと?)はわざとvolatileを付けることにより精確さを失わせて宣言できる。

次の関数はtrueを返すと保障されていない。
たとえ引数とそれぞれの積が「妥当な」値でも。

bool test (double a, double b) 
{ 
  double c, d; 
  c = a * b; 
  d = a * b; 
  return ( c == d ); 
} 

cとdをvolatileにすることでそれらが同じ値であることを保証する。
また同一であると比較し、no out of range conditionが起きないと仮定できる。

ようするにレジスタ上で「精確に」浮動小数点の値を持たせず、volatileをつけてわざとメモリ上で管理することで「だいたいあってる」的な判断ができる、ってことかな?
no out of range conditionはなんだろう・・・レジスタからオーバーフローしないってこと?
まぁvolatileの新しい使い道覚えたのでいいや。