Short Circuit, Ternary Operator and Precedence

In our previous post, we have discussed about operators in C#. There are few concepts that revolve around these operators which are easy to understand and some new operators for some specific scenarios.




Short Circuit Evaluation or Short Circuit in C#


We have logical operators such as && - AND and || - OR. && returns true if both the operands are true and || returns true if either of the operand is true. You can refer the truth table of these operators below - 

Truth Table For AND

 Operand A  Operand B  Result 
 false false false
 false true false
 true false false
 true true true
Truth Table For OR

 Operand A  Operand B  Result 
 false false false
 false true true
 true false true
 true true true

How to understand this truth table and relate it to AND and OR - suppose you have two boolean variables bool a = true; and bool b = false; Now if you execute statement like a && b, it will evaluate to false. Refer truth table for AND where Operand A is true and Operand B is false, result is false. So a && b is false. Same applies to OR i.e. if you execute a || b - result is true.

Now what is short circuiting? If you look at the truth table of AND, if either of the operand is false, result is false. So C# compiler evaluates the statement smartly by short circuiting the statement meaning if first operand is false then it does not evaluate the other operand and output it as false. Same goes for OR i.e. when first operator is true then compiler does not evaluate the second operand and output it as true.

Let us take one e.g. to make it more clear :

using System;

class Program
{
    static void Main(String[] args)
    {
        int a = 10;
        int b = 20;

        Console.WriteLine(a == 20 && ++b == 20); //false
        Console.WriteLine(b); //Prints 20 because first condition is false and due to short circuit second operand is not evaluated.

        Console.WriteLine(a == 10 && ++b == 20); //false
        Console.WriteLine(b); //Prints 21 because first condition is true, second condition is evaluated and value of b is incremented. 

        b = 20; //Resetting it to 20

        Console.WriteLine(a == 10 || ++b == 20); //true
        Console.WriteLine(b); // Prints 20 because first condition is true, second is not evaluated due to short circuit.

        Console.ReadKey();
    }
}
Output -

CheezyCode-CSharp-ShortCircuit



In simple words -

In an expression such as A && B, if A evaluates to false, then B is not evaluated because if either of the operator is false, output is false in case of AND(&&).
In an expression such as A || B, if A evaluates to true, then B is not evaluated because if either of the operator is true, output is true in case of OR(||).

Ternary Operator or Conditional Operator ( ?: )


Ternary operator is used for conditional expressions like if number is divisible by 2 then even otherwise odd. Let us take an e.g. to make it more clear - To check whether entered number is even or odd using ternary operator - 

using System;

class Program
{
    static void Main(String[] args)
    {
        int number;
        Console.WriteLine("Enter Number - ");
        string strNumber = Console.ReadLine();
        int.TryParse(strNumber, out number); // Converting string to integer "23" --> 23
        
        // condition ? expression1 : expression2 - Ternary Operator
        string status = number % 2 == 0 ? "Even" : "Odd"; // Check if number is divisible by 2 then even otherwise odd
        Console.WriteLine("Number Entered Is - " + status);        
        Console.ReadKey();
    }
}

Output -

CheezyCode-CSharp-Ternary-Operator


NOTE: There are pros and cons of everything. Some people avoid using ternary operator because of readability issues and some people like this operator due to less number of coding lines.


Operator Precedence


When there are multiple operators in an expression which operator will be evaluated first is decided by operator precedence. For e.g. a = b + c * d - in this expression, whether addition is performed first or multiplication or assignment is done first then addition. To solve this, we have operator precedence which decides the order of evaluation by grouping together the operands. In simple words, for above expression evaluation is done as a = b + (c * d) because * has higher precedence than +, so c and d are grouped together.

Note - For expressions like a == 20 && ++b == 20, operator precedence helps defining the grouping as  (a == 20) && ((++b) == 20). Now && is the top level operator and for this short circuiting is done. 

We will just provide the precedence of common operators - (Priority is from Top to Bottom - Top is highest priority and bottom is lowest priority)

 1.  Dot Operator, [ ], ()
 2.  NOT (!), Cast, Unary +, Unary -
 3.  * / %
 4.  Binary +, Binary -
 5.  Relational <  > <=  => == !=
 6.  Logical &&
 7.  Logical ||
 8.  Nullable
 9.  Ternary ?:
 10.  Assignment Operator =

Generally, you don't have to remember the above precedence table. Once you start programming, you will be able to write expressions of any kind. To avoid any confusion, you can use brackets ( ). For e.g. decimal a = (b * c) * d + (e / f ) - Here I want to evaluate b * c first, so i put the parenthesis around it.

Let us know if you have any query or concerns. Happy Reading (refer full series here - C# Tutorial Index )




Comments

Popular posts from this blog

Create Android Apps - Getting Started

Kotlin Type Checking and Smart Cast with Examples