Friday, September 10, 2010

Object Oriented Language: C++, Common Operators

Arithmetic Operators
Name Symbol Syntax
Addition
+ 1 + 2
Subtraction
- 3 - 1
Multiplication
* 6 * 6
Division
/ 9 / 3
Modulo
% 100 % 3
Pre-Increment
++ ++x
Post-Increment
++ x++
Pre-Decrement
-- --x
Post-Decrement
-- x--
Assignment
= x = 3

Compound Assignment
Name Symbol Syntax
Addition Assignment
+= x += 2
Subtraction Assignment
-= x -= 1
Multiplication Assignment
*= x *= 6
Division Assignment
/= x /= 3
Modulo Assignment
%= x %= 3
Bitwise AND Assignment
&= x &= 3
Bitwise OR Assignment
|= x |= 3
Bitwise XOR Assignment
^= x ^= 3
Bitwise left shift Assignment
<<= x <<= 3
Bitwise right shift Assignment
>>= x >>= 3

Relation and Equality Operators
Name Symbol Syntax
Equality
== x == y
Inequality
!= x != y
Greater Than
> x > y
Less Than
< x < y
Greater Than or Equal to
>= x >= y
Less Than or Equal to
<= x <= y

Logical Operators
Name Symbol Syntax
Logical Negation (not)
! !x
Logical AND
&& x && y
Logical OR
|| x || y

Of course, there are other operators, but they are out of scope of this lesson. We should all know the obvious, so basic arithmetic operators are not discussed. I'll start off with the modulo operator, %. It's easier to start with some simple examples.
int x = 100;

cout << x / 3; // will output 33
cout << x % 3; // will output 1

cout << x / 2; // will output 50
cout << x % 2; // will output 0

cout << x / 19; // will output 5
cout << x % 19; //will output 5

cout << 20 / x; // will output 0
cout << 20 % x; //will output 20
In C++, 100 / 3 = 33. This is called integer division, it is also the quotient of the division. 100 % 3 = 1. Modulo returns the remainder after computing the integer division. 100 / 3 = quotient, 33 100 % 3 = remainder, 1 If you still do not get the concept, try to write a program practicing integer division and modulo operation. Pre and post increment. x++ is a simplified version of writing x = x + 1, or x += 1. The difference of pre and post increment is the order of evaluation of the expression. Pre-increment does the increment before the expression is evaluated. Post-increment does the increment after the expression is evaluated.
int x = 5;
cout << ++x; // x is incremented, then outputs 6
// x is 6 now
cout << x++; // outputs 6, then x is incremented
cout << x; // outputs 7 since it was incremented in the last statement.

Addition assignment, +=. For instance, x += 2, can be rewritten as x = x + 2. The concept is the same with all the compound assignment operators.

Operators used for conditions:
int x = 25;
if( (x >= 10) && (x <= 99) ){
    cout << "x is greater than or equal to 10 AND less than or equal to 99" << endl;
    if( x != 50){
        cout << "x is not equal to 50";
        if ( x == 25 ){
            cout << "x is equal to 25";
        }
    } 
}
Please study short-circuit evaluation by yourself.

No comments:

Post a Comment