Saturday 7 January 2017

What is Operator Precedence? Difference between Prefix And Postfix Operators

Operator Precedence
Operator precedence defines the order in which various operators should be evaluated. It determines the grouping of terms in an expression. When two operators share an operand the operator with the higher precedence goes first. Operators with a higher precedence are applied before operators with a lower precedence. Certain operators have higher precedence than others;
For example, 1 + 2 * 3 is treated as 1 + (2 * 3), whereas 1 * 2 + 3 is treated as (1 * 2) + 3 since multiplication has a higher precedence than addition.
 Consider the following expression
int x = 4 + 3 * 2
here x is assigned 10, not 14 because operator * has higher precedence than +, so it first gets multiplied with (3 * 2) and then adds into 4.


Prefix Operators
The prefix operators are those in which the increment or decrement sign occurs before the variable. It is denoted by ++var; sign, it first performs the increment operation and then returns that incremented value.
For example
int x = 3;
int y = ++x; // y = 4, x = 4
In the above example, it increments x and uses the incremented value in the expression to print the value of x.

Postfix Operators
The postfix operators are those in which the incremented or decrement sign occurs after the variable. It is denoted by var++; sign. The postfix form first returns the current value of the expression and then performs the increment operation on that value.
 For example,
int x = 3;
int y = x++; // y = 3, x = 4
In the above example, it first prints the original value and then uses than original value to increment x.

No comments:

Post a Comment