Operations represent certain actions over operands (variables) involved in the operation.
Operations can be binary — performed on two operands, unary — performed on a single operand, ternary — performed on three operands.
Binary arithmetic operations:
- + — addition, adds the right operand to the left;
- - — subtraction, subtracts the right operand from the left;
- * — multiplication, multiplies the left and right operand;
- / — division, divides the left operand by the right. Division by zero is prohibited, otherwise you will get DivideByZeroException;
When dividing, keep in mind that if both operands represent integers, then the result will also be rounded to an integer:
- % — modulus, returns the remainder after dividing the left operand by the right;
Unary arithmetic operations:
- ++ — increment. The increment can be pre-fixed: ++x — first, the value of x is incremented by 1, and then its value is returned as the result of the operation. Also, increment can be post-fixed: x++ — first, the value of x is returned as the result of the operation, and then 1 is added to it:
- - -— decrement. Decreases the value of the operand by one, can also be pre-fixed and post-fixed:
So we looked at binary and unary operations. What happens if we write it like this?
Confused, right? Fortunately, C# has operator precedence. Precedence of arithmetic operations from highest to lowest:
- increment, decrement;
- multiplication, division, modulus;
- addition, subtraction;
Now ready to answer the example above? Order of operations:
- Post-increment (x = 19)
- Multiplication (y * z = 12)
- Subtraction (19–12 = 7)
Answer — 7.
For convenience, it could be written like this:
But with parentheses, we could change the order of operations, for example, as follows:
Think about the answer here, then you can check yourself via Visual Studio, just run code there and write output to the console or use breakpoint.
As we said, multiplication and division operations have the same precedence. So what’s the result will be here?
When operations have the same precedence, the order of calculation is determined by associativity. Depending on associativity, there are two types of operators.
- Left-associative operators that execute from left to right (Postfix Increment and Decrement, Multiplication, Division, Modulus, Additive);
- Right-associative operators that execute from right to left (Prefix Increment and Decrement Operators);
So, the result above will be 75, because multiplication and division operators are left associative.
After you go through all the operators, then you can check an article with the precedence and associativity of each operator, as a summary.
Previous article -> 2.5 Console Input/Output
Next article -> 2.7 Assignment Operators
Join to our community in Telegram — https://t.me/itifico
If you want to support me, you can buy me a cup of coffee and I will drink it when I write the next article :)
- Dinesh Chintalapudi — 3$
- Unknown — 5$
- Neisy — 3$