D語言邏輯運算子


下表列出了所有D語言支援的邏輯運算子。假設變數A=1和變數B=0,則:

運算子 描述 範例
&& 所謂邏輯AND運算子。如果這兩個運算元都為非零,則條件變為真。 (A && B) is false.
|| 所謂邏輯或運算子。如果任何兩個運算元為非零,則條件變為真。 (A || B) is true.
! 所謂邏輯非運算子。使用反轉其運算元的邏輯狀態。如果條件為真,則邏輯NOT運算子將為false。 !(A && B) is true.

範例

試試下面的例子就明白了所有的D程式設計語言的邏輯運算子:

import std.stdio;

int main(string[] args)
{
    int a = 5;
   int b = 20;
   int c ;

   if ( a && b )
   {
      writefln("Line 1 - Condition is true
" );
   }
   if ( a || b )
   {
      writefln("Line 2 - Condition is true
" );
   }
   /* lets change the value of  a and b */
   a = 0;
   b = 10;
   if ( a && b )
   {
      writefln("Line 3 - Condition is true
" );
   }
   else
   {
      writefln("Line 3 - Condition is not true
" );
   }
   if ( !(a && b) )
   {
      writefln("Line 4 - Condition is true
" );
   }
   return 0;
}

當編譯並執行上面的程式它會產生以下結果:

Line 1 - Condition is true

Line 2 - Condition is true

Line 3 - Condition is not true

Line 4 - Condition is true