Operators in C++

An operator is a symbol that causes the compiler to take an action. Operators act on operands, and in C++ all operands are expressions. In C++ there are several different categories of operators. Two of these categories are
• Assignment operators.
• Mathematical operators.
 
Assignment OperatorThe assignment operator (=) causes the operand on the left side of the assignment operator to have its value changed to the value on the right side of the assignment operator. The expression
x = a + b;
assigns the value that is the result of adding a and b to the operand x.An operand that legally can be on the left side of an assignment operator is called an lvalue. That which can be on the right side is called (you guessed it) an rvalue.
Constants are r-values. They cannot be l-values. Thus, you can write
x = 35; //
ok but you can't legally write
35 = x; // error, not an lvalue!
 
New Term: An lvalue is an operand that can be on the left side of an expression. An rvalue is an operand that can be on the right side of an expression. Note that all l-values are r-values, but not all r-values are l-values. An example of an rvalue that is not an lvalue is a literal. Thus, you can write x = 5;, but you cannot write 5 = x;.

Mathematical Operators
There are five mathematical operators: addition (+), subtraction (-), multiplication (*), division (/), and modulus (%).
Addition and subtraction work as you would expect, although subtraction with unsigned integers can lead to surprising results, if the result is a negative number. Below given Listing shows what happens when you subtract a large unsigned number from a small unsigned number.
 
Listing : A demonstration of subtraction and integer overflow.
1: // Listing given below - demonstrates subtraction and
2: // integer overflow
3: #include <iostream.h>
4:
5: int main()
6: {
7: unsigned int difference;
8: unsigned int bigNumber = 100;
9: unsigned int smallNumber = 50;
10: difference = bigNumber - smallNumber;
11: cout << "Difference is: " << difference;
12: difference = smallNumber - bigNumber;
13: cout << "\nNow difference is: " << difference <<endl;
14: return 0;
15: }
 
Output:
Difference is: 50
Now difference is: 4294967246
 
Analysis: The subtraction operator is invoked on line 10, and the result is printed on line 11, much as we might expect. The subtraction operator is called again on line 12, but this time a large unsigned number is subtracted from a small unsigned number. The result would be negative, but because it is evaluated (and printed) as an unsigned number, the result is an overflow.

Post a Comment

0 Comments