Arithmetic in c++ is quite straightforward. All of the numeric data types can be used to perform calculations. The C++ language provides the following arithmetic operators:
Operator | Meaning | Example | |
---|---|---|---|
+
|
Addition |
y = a + b;
|
|
+
|
positive |
y = +a;
|
|
-
|
subtraction |
|
|
-
|
Negative (inversion) |
y = -a;
|
|
*
|
multiplication |
y = a * b
|
|
/
|
division |
y = a / b
|
|
%
|
remainder |
y = a % b;
The % operator divides its first operand by the second (like
the division operator) but instead of returning the result, it returns
the remainder. So 35 % 10 is 5.
|
|
++
|
increment |
y++; ++y;
|
|
--
|
decrement |
y--; --y;
|
|
Note: |
There are two variants of each of these operators: a pre-increment such as ++x, and a post increment such as x++. The difference is that the pre increment increments the value of its operand and then returns a value, where as the post increment returns the value of its operand, then increments the operand. X=5;
Y=x++; //y is 5, but x is 6
X=5;
Y=++x; //x is 6 , so is y
|
||
+=
|
Self addition |
|
|
-=
|
Self subtraction |
|
|
*=
|
Self multiplication |
|
|
/=
|
Self division |
|
|
%=
|
Self remainder |
Where applicable, the above operators should be used in preference to the longhand version (i.e. use x+=y rather than x=x+y),as the self referencing version of the operation is likely to be implemented more efficiently than the equivalent longhand version |
Operator | Meaning | Example | |
---|---|---|---|
>
|
Greater than |
If (x>8)
|
|
>=
|
Greater than or equal |
If (x>=9)
|
|
==
|
Is equal to |
If (x==9)
|
|
<=
|
Less than or equal |
If (x<=9)
|
|
<
|
Less than |
If (x<10)
|
|
!=
|
Not equal |
If (x!=11)
|
|
&&
|
And |
If (x>8 && x<10)
|
|
||
|
Or |
If (x==9 || x==10)
|
|
Notes |
The terms in a compound || or && statement are always checked from left to right, so if the left most term invalidates (for &&) or proves (for ||) the condition, no further conditions are checked
|
||
!
|
Not |
If (!(x==10))
|