Operator Precedence

1.7 Operator Precedence

Consider the following statement:
X = 5 + 30 * 10
x will store 305. In this equation, the numbers 30 and 10are multiplied first, and the number 5 is added to their product.
Multiplication, division and modulus have higher order than addition and subtraction, which means that they’re performed first.
If two operators sharing an operand have the same precedence, they work according to their associativity. Associativity is either left to right or right to left.
Associativity of - (unary negation) is Right to left and * / + - is Left to right.
Some expressions and their values
Expression
Value
6 + 2 * 3
12
8 / 2 - 3
1
8 + 10 * 2 - 4
24
4 + 11 % 2 - 1
4
6 - 3 * 3 + 7 - 1
3

Combined Assignment Operator

Operator
Example
Meaning
+=
x += 5
x = x +5
-=
x -= 5
x = x - 5
*=
x *= 2
x = x * 2
%=
x %= 3
x = x % 3
/=x /= 4
x = x / 4

Increment and Decrement Operators

Increment operator ++ is used to add 1 to variable's value, and decrement operator -- is used to subtract 1 from its value.
Increment and decrement operators each have two forms: pre and post.
The syntax of the increment operator is:
Pre-increment: ++variable
Post-increment: variable++
The syntax of the decrement operator is:
Pre-decrement: --variable
Post-decrement: variable--
Consider the following code:
int x, y, z;
x = 24;
y = x++; // y is given x’s value(24)before it is incremented
   // and x is then incremented to 25
z = ++x; // x is incremented to 25, and z is given x’s value
          

No comments:

Post a Comment

Pages