Operators | Description |
---|---|
+ | Unary plus: needs one operand. |
- | Unary minus: needs one operand. |
+ | Addition: needs two operands. |
- | Subtraction: needs two operands. |
* | Multiplication: needs two operands. |
/ | Division: needs two operands.
|
% | Modulus: needs two operands
|
++ | Increment by one; can be prefix or postfix; as prefix has highest precedence |
-- | Decrement by one; can be prefix or postfix; as prefix has highest precedence |
Look at the following example, and decide what is written by each of the output statements, then click the grey boxes to confirm your answers.
/************************************************************* * * This program demonstrates the precedence of the operators. * *************************************************************/ #include <iostream> using namespace std; int main () { cout << 4 + 3 * 5 << endl; 19 cout << (4 + 3) * 5 << endl; 35 cout << 4 * 5 % 3 + 2 << endl; 4 cout << (4 * (5 % 3) + 2) << endl; 10 return 0; }
Type changes can be made explicit by placing the value to be changed in parentheses and placing the name of the new type before it. This is called type casting or type conversion. For example:
intValue = 10.66; and
intValue = int(10.66) produce the same result 10.
There are times when you need to do this to get the arithmetic results you want. Consider the results of this sample program:
#include <iostream>
using namespace std;
int main()
{
int i = 3, j = 4;
float x = 3, y = 4;
cout << showpoint; // be sure full precision shows
cout << "Int operands: " << i << " / " << j << " = " << i/j << endl;
cout << "Float operands: " << x << " / " << y << " = " << x/y << endl;
cout << "Mixed operands: " << i << " / " << y << " = " << i/y << endl;
cout << "Int operands, one typecast to float: "
<< float(i) << " / " << j << " = " <<float(i)/j << endl;
cout << "Typecasting is not permanent: " << i << endl;
cout << "Float operands, both typecast to int: "
<< int(x) << " / " << int(y) << " = " << int(x)/int(y) << endl;
cout << "Modulo doesn't normally work with floats: "
<< y << " % " << x << " = " << int(y)%int(x) << endl;
return 0;
}
In summary, we have explicit and implicit data type conversion.
Type coercion The implicit (automatic) conversion of a value from one data type to another.
Type casting The explicit conversion of a value from one data type to another; also called type conversion.