Operator Precedence
Part of the Logic & Flow section of Coddy's C# journey — lesson 38 of 66.
Operator precedence determines the order in which operators are evaluated in an expression. Understanding precedence is crucial for writing correct logical expressions.
Look at this example:
int result = 5 + 3 * 2;What's the value of result? It's 11, not 16, because multiplication has higher precedence than addition.
Here's a simplified precedence order (from highest to lowest):
- Parentheses
() - Multiplication/Division
* / % - Addition/Subtraction
+ -
- Comparison operators
< > <= >= - Equality operators
== !=
- Logical AND
&& - Logical OR
|| - Assignment operators
= += -=etc.
Let's see how this applies:
bool result = 5 > 3 && 10 < 20 || 7 == 8;First, the comparisons are evaluated: 5 > 3 is true, 10 < 20 is true, and 7 == 8 is false.
Then, logical AND: true && true is true.
Finally, logical OR: true || false is true.
So result is true.
Use parentheses to make your code clearer:
bool result = (5 > 3 && 10 < 20) || (7 == 8);Challenge
EasyCreate a method named EvaluateExpression that takes three integers (a, b, c) and returns a boolean.
Your method should return the result of this expression:a > b || a == c && b < c
Then, create another method named EvaluateWithParentheses that evaluates:(a > b || a == c) && b < c
Your program should read three integers from the console and print the results of both evaluations on separate lines.
Cheat sheet
Operator precedence determines the order in which operators are evaluated in an expression.
Precedence order (from highest to lowest):
- Parentheses
() - Multiplication/Division
* / % - Addition/Subtraction
+ - - Comparison operators
< > <= >= - Equality operators
== != - Logical AND
&& - Logical OR
|| - Assignment operators
= += -=etc.
Example:
int result = 5 + 3 * 2; // result is 11, not 16Complex logical expression:
bool result = 5 > 3 && 10 < 20 || 7 == 8;
// Evaluates to: true && true || false = true || false = trueUse parentheses for clarity:
bool result = (5 > 3 && 10 < 20) || (7 == 8);Try it yourself
using System;
class Program
{
public static bool EvaluateExpression(int a, int b, int c)
{
// Write your code here
}
public static bool EvaluateWithParentheses(int a, int b, int c)
{
// Write your code here
}
static void Main(string[] args)
{
Console.WriteLine("Enter three integers:");
int a = int.Parse(Console.ReadLine());
int b = int.Parse(Console.ReadLine());
int c = int.Parse(Console.ReadLine());
// Call your methods and print the results
}
}This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Logic & Flow
1Multi-dimensional Arrays
2D Arrays BasicsDeclaring and Initializing 2DAccessing 2D Array ElementsNested Loops with 2D ArraysJagged ArraysCommon Matrix OperationsRecap - Multi-dimensional4Flow Control Techniques
Early ReturnsGuard ClausesJump Statements (goto)Break and ContinueFlatten Nested Conditionals7Logical Operators Advanced
Short-Circuit EvaluationConditional Logical OperatorsOperator PrecedenceRecap - Advanced Operators2Advanced Decision Making
Multiple ConditionsComplex Boolean LogicIf vs. Switch ComparisonNested Switch StatementsRecap - Advanced Decisions5Exception Handling
Try-Catch BasicsException TypesMultiple Catch BlocksWorking with FilesFinally BlockUsing vs. Try-FinallyCustom ExceptionsRecap - Error Handling3Loop Enhancements
Loop PerformanceIterating ComplexEach Loop TypeRefactoring LoopsRecap - Optimized Loops6Null Handling
Null Reference BasicsNullable Value TypesNull Checking PatternsDefensive ProgrammingRecap - Null Safety