10x Blogs Directory

Wednesday, February 25, 2009

Logical Operators

  • Logical operators have one or two boolean operands that yield a boolean result.
  • There are six logical operators:
    - && (logical AND)‏
    -& (boolean logical AND)‏
    - (logical OR)‏
    - (boolean logical inclusive OR)‏
    -^ (boolean logical exclusive OR)‏
    -! (logical NOT)‏


&&(logical) and &(boolean logical) AND

  • The basic difference between && and & operators :
    -&& supports short-circuit evaluations (or partial evaluations), while & doesn't.
  • Given an expression:exp1 && exp2
    -&& will evaluate the expression exp1, and immediately return a false value is exp1 is false. -If exp1 is false, the operator never evaluates exp2 because the result of the operator will be false regardless of the value of exp2.
  • In contrast, the & operator always evaluates both exp1 and exp2 before returning an answer.


(logical) and (boolean logical) inclusive OR

  • The basic difference between and I operators :
    - supports short-circuit evaluations (or partial evaluations), while doesn't.
  • Given an expression:exp1 exp2
    - will evaluate the expression exp1, and immediately return a true value is exp1 is true
    -If exp1 is true, the operator never evaluates exp2 because the result of the operator will be true regardless of the value of exp2.
    -In contrast, the operator always evaluates both exp1 and exp2 before returning an answer.


^ (boolean logical exclusive OR)

  • The result of an exclusive OR operation is TRUE, if and only if one operand is true and the other is false.
  • Note that both operands must always be evaluated in order to calculate the result of an exclusive OR.


! ( logical NOT)‏

  • The logical NOT takes in one argument, wherein that argument can be an expression, variable or constant.


Conditional Operator (?:)‏

  • The conditional operator ?:
    -is a ternary operator.
  • This means that it takes in three arguments that together form a conditional expression.
    -The structure of an expression using a conditional operator isexp1?exp2:exp3
    wherein,
    exp1 - is a boolean expression whose result must either be true or false
    -Result:
    If exp1 is true, exp2 is the value returned.
    If it is false, then exp3 is returned.