2012-05-08 4 views
3

ブール演算(==!=>&&||など)は、真偽を表すのに常に同じ値を持つことを保証していますか?言い換えれば、真の場合は常に正の定数を返しますか、それが正の数であるという唯一の保証ですか?ブール演算の結果を比較できますか?

私がこれを求めている理由は、以下のような記述が有効かどうかを知ることです。両方のポインタがNULLまたは両方のポインタがどこかを指している(必ずしも同じ場所である必要はない)場合、その式は真でなければなりません。

if ((ptr1 == NULL) == (ptr2 == NULL)) 
+0

この文は短絡回路評価を呼び出すでしょうか?とにかく、「if(((ptr1 == NULL)&&(ptr2 == NULL))||((ptr1!= NULL)&&(ptr2!= NULL)))」という表現は、私のために、それは声明の意図を少しはっきりさせます。 –

+0

申し訳ありません@ポールマンタ私は私の考えを完了する前に送信キーを押す! :-( –

+0

@RobWellsそれは私が尋ねた1が任意の割合でたくさん短くなっている。明確にされているバージョン議論の余地だ、と私は誰もがので、私は使用しない本当の理由はありません推測を意味することになっているものを私に求めて取得していませんそれは2つの数値が両方とも負か正のどちらであるかを調べるために '(a * b)> 0'を実行するのと同じスタイルです。 –

答えて

7

はい、がCによってブール値として積分値の解釈のルールは0が偽であり、任意の他の値が真(A)で、比較演算の結果は常に1又は0であると述べています。

したがって、式(a == b)は決して42を与えません。

標準(C11)の関連ビットが6.5 Expressions下のすべてである:

6.5.8/6: Each of the operators < (less than), > (greater than), <= (less than or equal to), and >= (greater than or equal to) shall yield 1 if the specified relation is true and 0 if it is false.

6.5.9/3: The == (equal to) and != (not equal to) operators are analogous to the relational operators except for their lower precedence. Each of the operators yields 1 if the specified relation is true and 0 if it is false.

6.5.13/3: The && operator shall yield 1 if both of its operands compare unequal to 0; otherwise, it yields 0.

6.5.14/3: The || operator shall yield 1 if either of its operands compare unequal to 0; otherwise, it yields 0.

あなたの質問で明示的に言及したものすべてを網羅しています。

6.5.3.3/5: The result of the logical negation operator ! is 0 if the value of its operand compares unequal to 0, 1 if the value of its operand compares equal to 0.


(a)の:私は(私の頭の上から)考えることができる唯一の他のブール演算も覆われている論理NOT演算子!次のとおりです。 ifwhiledoおよびforを扱うC11セクションを参照してください。これらのセクションには、いずれも//"the expression compares unequal to zero"の場合に起こる行に沿った言語が含まれています。具体的には:

6.8.4.1/2: In both forms [of the if statement, one with and one without an else clause], the first substatement is executed if the expression compares unequal to 0. In the else form, the second substatement is executed if the expression compares equal to 0.

6.8.5/4: An iteration statement [while, do and for] causes a statement called the loop body to be executed repeatedly until the controlling expression compares equal to 0.

1

はい。

演算子によって生成される値は、真で1、偽で0です。

0

  • 否定演算子(!

  • 関係演算子(の結果、><=>=

  • 等価演算子(==!=

    論理演算子(&&||

のいずれか0(偽のint値)又は1 (真)。

関連する問題