<<

1.6.9 ++ Operators  An operator is a symbol that tells the compiler to perform specific mathematical or logical manipulations. C++ is rich in built-in operators and provides following type of operators: a) Arithmetic Operators b) Relational Operators c) Logical Operators d) Bitwise Operators e) Assignment Operators f) Misc Operators ARITHMETIC OPERATORS:  There are following arithmetic operators supported by C++ language:  Assume variable A holds 10 and variable B holds 20 then: Operator Description Example + Adds two operands A + B will give 30 Subtracts second operand from the A - B will give - first -10 A * B will give * Multiply both operands 200 / Divide numerator by de-numerator B / A will give 2 Modulus Operator and remainder of % B % A will give 0 after an integer division Increment operator, increases ++ A++ will give 11 integer value by one Decrement operator, decreases -- A-- will give 9 integer value by one

RELATIONAL OPERATORS:  There are following relational operators supported by C++ language  Assume variable A holds 10 and variable B holds 20 then: Operato Description Example r Checks if the value of two operands is equal or not, if (A == B) is not == yes then condition becomes true. true. Checks if the value of two operands is equal or not, if != (A != B) is true. values are not equal then condition becomes true. > Checks if the value of left operand is greater than the (A > B) is not value of right operand, if yes then condition becomes true. true. Checks if the value of left operand is less than the < value of right operand, if yes then condition becomes (A < B) is true. true. Checks if the value of left operand is greater than or (A >= B) is not >= equal to the value of right operand, if yes then true. condition becomes true. Checks if the value of left operand is less than or <= equal to the value of right operand, if yes then (A <= B) is true. condition becomes true.

LOGICAL OPERATORS:  There are following logical operators supported by C++ language Operato Description Example r Called Logical AND operator. If both the (A && B) is && operands are non zero then condition becomes false. true. Called Logical OR Operator. If any of the two (A || B) is || operands is non zero then condition becomes true. true. Called Logical NOT Operator. Use to reverses !(A && B) is ! the logical state of its operand. If a condition is true. true then Logical NOT operator will make false.

BITWISE OPERATORS:  A bitwise operator works on bits and performs bit by bit operation. The truth tables for &, |, and ^ are as follows:

p q p & q p | q p ^ q 0 0 0 0 0 0 1 0 1 1 1 1 1 1 0 1 0 0 1 1

Assume if A = 60; and B = 13; Now in binary format they will be as follows: A = 0011 1100 B = 0000 1101 ------A&B = 0000 1100 A|B = 0011 1101 A^B = 0011 0001 ~A = 1100 0011  The Bitwise operators supported by C++ language are listed in the following table. Assume variable A holds 60 and variable B holds 13 then: Operator Description Example Binary AND Operator copies a bit to the result if it exists (A & B) will give 12 which & in both operands. is 0000 1100 Binary OR Operator copies a bit if it exists in either (A | B) will give 61 which is | operand. 0011 1101 Binary XOR Operator copies the bit if it is set in one (A ^ B) will give 49 which is ^ operand but not both. 0011 0001 Binary Ones Complement Operator is unary and has the (~A ) will give -60 which is ~ effect of 'flipping' bits. 1100 0011 Binary Left Shift Operator. The left operands value is A << 2 will give 240 which << moved left by the number of bits specified by the right is 1111 0000 operand. Binary Right Shift Operator. The left operands value is A >> 2 will give 15 which is >> moved right by the number of bits specified by the right 0000 1111 operand.

ASSIGNMENT OPERATORS:  There are following assignment operators supported by C++ language: Operator Description Example Simple assignment operator, Assigns values from right side C = A + B will assign = operands to left side operand value of A + B into C Add AND assignment operator, It adds right operand to the left C += A is equivalent to C += operand and assign the result to left operand = C + A Subtract AND assignment operator, It subtracts right operand C -= A is equivalent to C -= from the left operand and assign the result to left operand = C - A Multiply AND assignment operator, It multiplies right operand C *= A is equivalent to C *= with the left operand and assign the result to left operand = C * A Divide AND assignment operator, It divides left operand with C /= A is equivalent to C /= the right operand and assign the result to left operand = C / A Modulus AND assignment operator, It takes modulus using C %= A is equivalent to C %= two operands and assign the result to left operand = C % A C <<= 2 is same as C = C <<= Left shift AND assignment operator << 2 C >>= 2 is same as C = C >>= Right shift AND assignment operator >> 2 C &= 2 is same as C = C &= Bitwise AND assignment operator & 2 C ^= 2 is same as C = C ^ ^= bitwise exclusive OR and assignment operator 2 |= bitwise inclusive OR and assignment operator C |= 2 is same as C = C | 2

MISC OPERATORS  There are few other operators supported by C++ Language. Operator Description sizeof operator returns the size of a variable. For example sizeof(a), sizeof where a is integer, will return 4. Conditional operator. If Condition is true ? then it returns value X : Condition ? X : Y otherwise value Y Comma operator causes a sequence of operations to be performed. The , value of the entire comma expression is the value of the last expression of the comma-separated list. Member operators are used to reference individual members of classes, . (dot) and -> (arrow) structures, and unions. Casting operators convert one data type to another. For example, Cast int(2.2000) would return 2. Pointer operator & returns the address of an variable. For example &a; & will give actual address of the variable. Pointer operator * is pointer to a variable. For example *var; will pointer * to a variable var.

OPERATORS PRECEDENCE IN C++:  Operator precedence determines the grouping of terms in an expression.  This affects how an expression is evaluated.  Certain operators have higher precedence than others; for example, the multiplication operator has higher precedence than the addition operator:  For example x = 7 + 3 * 2;  Here x is assigned 13, not 20 because operator * has higher precedence than + so it first get multiplied with 3*2 and then adds into 7.  Here operators with the highest precedence appear at the top of the table; those with the lowest appear at the bottom.  Within an expression, higher precedence operators will be evaluated first. Category Operator Associativity Postfix () [] -> . ++ - - Left to right Unary + - ! ~ ++ - - (type)* & sizeof Right to left Multiplicative * / % Left to right Additive + - Left to right Shift << >> Left to right Relational < <= > >= Left to right Equality == != Left to right Bitwise AND & Left to right Bitwise XOR ^ Left to right Bitwise OR | Left to right Logical AND && Left to right Logical OR || Left to right Conditional ?: Right to left Assignment = += -= *= /= %=>>= <<= &= ^= |= Right to left Comma , Left to right

Example program // compound assignment operators

#include using namespace std;

int main () { int a, b=3; a = b; a+=2; // equivalent to a=a+2 cout << a; return 0; }

1.6.10 REFERENCING (&) AND DEREFERENCING (*) OPERATORS

 The & and * operators are used for referencing and dereferencing.  The & symbol is also used in C++ to define reference types, and as a bitwise AND operator.  We can also use the asterisk as an operator to deference a pointer and as the multiplication operator.

C++ References  A reference variable is an alias, that is, another name for an already existing variable.  Once a reference is initialized with a variable, either the variable name or the reference name may be used to refer to the variable.  Once a reference is initialized to an object, it cannot be changed to refer to another object. Pointers can be pointed to another object at any time.  A reference must be initialized when it is created. Pointers can be initialized at any time

Referencing Operator (&)  The referencing operator is used to define referencing variable.  A reference variable prepares an alternative (alias) name for previously defined variable.  The syntax of the referencing operator is given below. Syntax: Data-type & reference variable name = variable name Example: int qty=10; int & qt=qty;  Here, qty is already declared and initialized.  The second statement defines an alternative variable name i.e., qt to variable qty.  If both printed variables display the same value, any change made in one of the variable causes change in both the variables Following example makes use of references on int and double: #include

using namespace std;

int main () { // declare simple variables int i; double d;

// declare reference variables int& r = i; double& s = d;

i = 5; cout << "Value of i : " << i << endl; cout << "Value of i reference : " << r << endl;

d = 11.7; cout << "Value of d : " << d << endl; cout << "Value of d reference : " << s << endl;

return 0; } When the above code is compiled together and executed, it produces following result: Value of i : 5 Value of i reference : 5 Value of d : 11.7 Value of d reference : 11.7  References are usually used for function argument lists and function return values. So following are two important subjects related to C++ references which should be clear to a C++ programmer: Concept Description References as C++ supports passing references as function parameters parameter more safely than parameters. Reference as return You can return reference from a C++ function like value a any other data type can be returned.

Dereferencing operator(*)  The asterisk(*) is a variable expression used to declare a pointer to a given type.  Example int *x; where x is a pointer of the integer type, if the operand is a “pointer to function”, the result is a function declarator

REFERENCE AND DEREFERENCE OPERATORS  In the example above we used ampersand sign (&).  This sign is called the reference operator.  If the reference operator is used you will get the “address of” a variable.  In the example above we said: ptr_p = &x;.  In words: store the address of the variable x in the pointer ptr_p.  We also used the asterisk sign (*) in the cout statement.  This sign is called the dereference operator.  If the dereference operator is used you will get the “value pointed by” a pointer.  So we said: cout << *ptr_p;. In words: print (or put into the stream) the value pointed by ptr_p. (It will print the contents of integer x.)  The asterisk (*) sign in the declaration of the pointer does not mean “value pointed by”, it only means that it is a pointer (it is part of its type compound specifier).  It should not be confused with the dereference operator.  They are simply two different things represented with the same sign.  So we can say:  & is the reference operator and can be read as “address of”.  * is the dereference operator and can be read as “value pointed by”. USING POINTERS TO PASS VALUES  In the example above we used an integer ‘x’ of which we stored the “address of” into a pointer ‘ptr_p’.  But it is also possible to use a pointer to pass a value to a variable.  Take a look at the next example:

#include using namespace std;

int main () { int x; int * ptr_p;

ptr_p = &x; *ptr_p = 5;

cout << x; return 0; }

 Note: We can see that no value is stored in x as in the previous example (x = 5 ).  But the result is the same.  First we store the address of x into the pointer ptr_p.  Then we say we want the value 5 stored at the address where the pointer is pointing to (in this case x).  So we can see we can use pointers to pass values to other variables.

1.6.11 ACCESS OPERATOR

 The variables declared in C++ programs are totally different from other languages.  We can use the same variable names in the C++ program in separate blocks.  The declaration of the same variable refers to different memory locations.  When we declare a variable it is available only to specific part or block of the program.  The remaining block or other function cannot access the variable.  The area or block of the C++ program from where the variable can be accessed is known as the scope of variables.  The scope access (or resolution) operator :: (two ) allows a programmer to access a global (or file duration) name even if it is hidden by a local re-declaration of that name.  A variable can be either of global or local scope. A global variable is a variable declared in the main body of the source code, outside all functions, while a local variable is one declared within the body of a function or a block. Scope of variables

 Global variables can be referred from anywhere in the code, even inside functions, whenever it is  after its declaration.  The scope of local variables is limited to the block enclosed in braces ({}) where they are declared. For example, if they are declared at the beginning of the body of a function (like in function main) their scope is between its declaration point and the end of that function.

1.6.12 MEMORY MANAGEMENT OPERATORS

 In C language, we have studied the function malloc( ), calloc( ) and realloc( ) to allocate memory dynamically at run time in the program.  The free( ) function is used to release the resources allocated by these functions.  C++ allows us to use these functions.  In addition, C++ provides operators which help us to allocate and release the memory in an easy way than these functions.  These new operators are new and delete.  The new operator creates an object and delete destroys the object.  These operators are easy in writing as compared to malloc( ) and calloc( ).

1.6.13 COMMA OPERATOR

 In C++, every statement of the program is terminated by semi-colon (;).  C++ allows us to terminate a statement using comma operator after satisfying the following rules: (1) The variable declaration statements should be terminated by semi-colon. (2) The statements followed by declaration statements like clrscr( ), cin, cout can be terminated by comma operator. (3) C++ permits declaration of variables at any place in program but such declaration is not allowed in between the statements terminated by comma operator. The initialization of previously declared variables can be done. (4) The last statement of the program must be terminated by semi-colon.

COMMA IN PLACE OF CURLY BRACES  The {} (curly braces) are used to define the body of a function and scope of the control statements.  The opening curly brace ({) indicates starting of the scope and (}) closing curly brace indicates the end of the scope.  It is also possible to use comma operator in condition and loop statement in place of {} to indicate the scope of the statement.  The use of comma operator is not allowed in definition of function.  The following declaration is invalid: main( ) , , Following program explains the use of comma operator with conditional and loop statements. A program to use comma operator in if..else structure as scope indicator. # include # include void main( ) { int x; clrscr( ), x=10; if (x==10) // if block cout <