トップ回答者
三項条件演算子の評価結果がおかしい (Visual Studio 2010 MSVC10)

質問
回答
-
Conditional-Expression Operator(? :)とUsual Arithmetic Conversionsに対する理解が足りていません。
三項演算子にはこのように記述されています。
If expression or conditional-expression has integral or floating type (their types can be different), the operator performs the usual arithmetic conversions. The type of the result is the type of the operands after conversion.
今回、expressionが ~0ULL(unsigned long long) でconditional-expressionが (value / 2.0 + .5)(接尾語を含まない浮動小数点数なのでdouble) なのでこれに該当します。次に数値変換ですが、
If the above condition is not met and either operand is of type double, the other operand is converted to type double.
今回、一方がdoubleなのでこれに該当し、他方のunsigned long longはdoubleに変換されます。
最後にdouble値がuint64_tに変換された上で変数xに代入されます。
MSDNのC言語から引用しましたが、もちろんVisual C++に限定した話ではなく、C言語仕様でこのように定められているので、どの書籍を参照しても同じ記述がされているでしょうし、他のコンパイラーも同じ動作をします。
すべての返信
-
Conditional-Expression Operator(? :)とUsual Arithmetic Conversionsに対する理解が足りていません。
三項演算子にはこのように記述されています。
If expression or conditional-expression has integral or floating type (their types can be different), the operator performs the usual arithmetic conversions. The type of the result is the type of the operands after conversion.
今回、expressionが ~0ULL(unsigned long long) でconditional-expressionが (value / 2.0 + .5)(接尾語を含まない浮動小数点数なのでdouble) なのでこれに該当します。次に数値変換ですが、
If the above condition is not met and either operand is of type double, the other operand is converted to type double.
今回、一方がdoubleなのでこれに該当し、他方のunsigned long longはdoubleに変換されます。
最後にdouble値がuint64_tに変換された上で変数xに代入されます。
MSDNのC言語から引用しましたが、もちろんVisual C++に限定した話ではなく、C言語仕様でこのように定められているので、どの書籍を参照しても同じ記述がされているでしょうし、他のコンパイラーも同じ動作をします。