0% found this document useful (0 votes)
4 views17 pages

Constant Operators in C++ Types of Operator: I. II. IV

The document covers lectures on constants and operators in C++ programming, detailing various types of constants such as literal, symbolic, and enum constants. It also explains different categories of operators including arithmetic, relational, logical, bitwise, assignment, and special operators, along with examples for each. Additionally, it introduces advanced operators like referencing, scope resolution, and memory management operators, emphasizing their usage and syntax.

Uploaded by

My pat
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views17 pages

Constant Operators in C++ Types of Operator: I. II. IV

The document covers lectures on constants and operators in C++ programming, detailing various types of constants such as literal, symbolic, and enum constants. It also explains different categories of operators including arithmetic, relational, logical, bitwise, assignment, and special operators, along with examples for each. Additionally, it introduces advanced operators like referencing, scope resolution, and memory management operators, emphasizing their usage and syntax.

Uploaded by

My pat
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 17

CSE/C++/Module-I/Trilochan Rout/Lecture: 7, 8, 9 1

IIIT, BHUBANESWAR
Dept. Comp. Sc. & Engg.
C++ and Object Oriented Programming
Lecture: 7, 8,9

Constant & Opeartor

I. Constant II. Operators in C++ IV. Types of Operator


Lecture: 7:
I. Constants:
 The constants are the values which do not change during the execution of a
program.
 There are different types of constant are present in C++.
 Literal Constant:
 A literal constant is directly assigned to a variable.
Example:
int x = 50;
float y = 10.28;
char ch = ‘Z’;
char it[ ]= “hello”;
 It includes integers, floating, characters and string constants.
 Symbolic Constant:
 They are defined in the same way as variables, but after initialization of
constants the assigned value cannot be altered.
 This constants can be defined in the following 3 ways:
I. # define (Macro Substitution)
- The # define preprocessor directive can be used for defining
symbolic constant.
Example:
# define pi 3.14
- It means every time when the preprocessor finds the word ‘pi’, it
substitutes it with 3.14

Example:
CSE/C++/Module-I/Trilochan Rout/Lecture: 7, 8, 9 2

#include <iostream>
Using namespace std;
#define PI 3.14
int main()
{
float radius, area;
cout<<"Enter the radius: ";
cin>>radius
// Notice, the use of PI
area = PI*radius*radius;

cout<<” Area=” <<area;


return 0;
}
II. The ‘const’ keyword
- By using the ‘const’ keyword we can define the symbolic constant.
- So these types of variables are also known as invariant.

Example:
Const int num = 150;
num = 100; //error, constant variable can’t modified.

- Here the value of num always remain equal to 150 and cannot be
changed at run-time.

Example:
#include<iostream>
using namespace std;
int main()
{
const int sunday =0; //const Sunday = 0
const int monday = 1;
int ch;
cout<<” enter the day code (0 or 1)”;
cin>>ch;0
if( ch == sunday)
cout<<”\n It’s a Holiday”;
else
cout<<”\n Nooo!!! It’s a working day”;
return 0;
}
Output:
Enter the day code(0 or 1)
1
Nooo. It’s a working day

III.The ‘enum’ keyword


CSE/C++/Module-I/Trilochan Rout/Lecture: 7, 8, 9 3

- We already know that by using ‘enum’ keyword we can assign


constant number to different names.
- If constant number not assigned to the name, then by default its
value is zero.

Example:
enum color {black, white, blu, red, green};

- Here the value for black is 0, white is 1, blue is 2, red is 3, green is

4.

enum color {black, white, blue=5, red, green=15};

- Here the value for black is 0, white is 1, blue is 5, red is 6, green is

15.

- We can define enum data without tag name.

Example:

Enum { a, b, c, d};//enum is declared without tag name or enum

variable name

or enum { a=5, b=10, c=15, d=20};


CSE/C++/Module-I/Trilochan Rout/Lecture: 7, 8, 9 4

Lecture: 8:
II. Operators in C++:
 Operator is an instruction to the compiler or interpreter specified by a single or
double symbol to perform certain operations with constants and variable.
 C++ supports all C 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 the following types of operators:
 Arithmetic Operators
 Relational Operators
 Logical Operators
 Bitwise Operators
 Assignment Operators
 Increment / Decrement Operators
 Special Operator

Arithmetic Operators:
 There are following arithmetic operators supported by C++ language:
 Assume variable A holds 10 and variable B holds 20, then:

Operat Description Example


or
+ Adds two operands A + B will give 30

- Subtracts second operand from the first A - B will give -10

* Multiplies both operands A * B will give 200

/ Divides numerator by de-numerator B / A will give 2

Modulus Operator and remainder of after


% B % A will give 0
an integer division

a=20
b=2
C=a%b
CSE/C++/Module-I/Trilochan Rout/Lecture: 7, 8, 9 5

Relational Operators:
 There are following relational operators supported by C++ language
 Assume variable A holds 10 and variable B holds 20, then:

Operat Description Example


or
Checks if the values of two operands are
(A == B) is not
== equal or not, if yes then condition becomes
true.
true.
Checks if the values of two operands are
!= equal or not, if values are not equal then (A != B) is true.
condition becomes true.
Checks if the value of left operand is greater
(A > B) is not
> than the value of right operand, if yes then
true.
condition becomes true.
Checks if the value of left operand is less than
< the value of right operand, if yes then (A < B) is true.
condition becomes true.
Checks if the value of left operand is greater
(A >= B) is not
>= than or equal to the value of right operand, if
true.
yes then condition becomes true.
Checks if the value of left operand is less than
<= or equal to the value of right operand, if yes (A <= B) is true.
then condition becomes true.
Logical Operators:
 There are following logical operators supported by C++ language
 Assume variable A holds 1 and variable B holds 0, then:

Operat Description Example


or

Called Logical AND operator. If both the


(A && B) is
&& operands are non-zero, then condition
false.
becomes true.

Called Logical OR Operator. If any of the


|| two operands is non-zero, then condition (A || B) is true.
becomes true.

Called Logical NOT Operator. Use to


reverses the logical state of its operand. If a !(A && B) is
!
condition is true, then Logical NOT operator true.
will make false.

Increment / Decrement Operators

Increment operator, increases integer value A++ will give


++
by one 11
CSE/C++/Module-I/Trilochan Rout/Lecture: 7, 8, 9 6

Decrement operator, decreases integer value


-- A-- will give 9
by one

Bitwise Operators:
 Bitwise operator works on bits and performs bit-by-bit operation.
 The Bitwise operators supported by C++ language are listed in the following
table. Assume variable A holds 60 and variable B holds 13, then:

Operat Description Example


or
Binary AND Operator copies a bit to the (A & B) will give 12 which is
&
result if it exists in both operands. 0000 1100
Binary OR Operator copies a bit if it (A | B) will give 61 which is
|
exists in either operand. 0011 1101
Binary XOR Operator copies the bit if it (A ^ B) will give 49 which is
^
is set in one operand but not both. 0011 0001
Binary Ones Complement Operator is (~A ) will give -61 which is
unary and has the effect of 'flipping' 1100 0011 in 2's
~
bits. complement form due to a
signed binary number.
Binary Left Shift Operator. The left A << 2 will give 240 which is
operands value is moved left by the 1111 0000
<<
number of bits specified by the right
operand.
Binary Right Shift Operator. The left A >> 2 will give 15 which is
operands value is moved right by the 0000 1111
>>
number of bits specified by the right
operand.
Explanation:
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
Assignment Operators:
 There are following assignment operators supported by C++ language:
CSE/C++/Module-I/Trilochan Rout/Lecture: 7, 8, 9 7

Operator Description Example

Simple assignment operator,


C = A + B will assign value of A +
= Assigns values from right side
B into C
operands to left side operand

Add AND assignment operator, It


adds right operand to the left
+= C += A is equivalent to C = C + A
operand and assign the result to
left operand
CSE/C++/Module-I/Trilochan Rout/Lecture: 7, 8, 9 8

Special Operator
 There are few other operators supported by C++ Language.
Operator Description
sizeof operator returns the size of a variable. For
Sizeof
example, sizeof(a), where a is integer, will return 4.
Conditional operator. If Condition is true ? then it
Condition ? X : Y
returns value X : 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.

Lecture: 9:
 Additional C++ Operator:
o << → Insertion Operator
o >>→ Extraction Operator
o &→ Referencing Operator
o : : → Scope Resolution Operator
o : :* →Pointer-to-member declaration
o →* →Pointer-to-member Operator
o .* →Pointer-to-member Operator
o new →Memory allocation Operator
o delete → Memory release Operator
o endl → Line feed Operator
o setw → Field width Opeartor
 Referencing(&) Operator:
- This operator is used to define referencing variable.
- A reference variable provides an alias(alternative names) for a previously
defined variable.
Syntax:
datatype &newname = original name;
Example:
int qty = 10;
int &qt = qty; → qt is an alternative name for qty
If we display the both variables by using cout statement,
cout<<qty;
cout<<qt;
Both will give the value 10. Changes madeto anyone it will affect to both.
Features:
- A reference variable must be initialized at the time of declaration.
- Once reference variable is declared, it should not refer to any other
variable.
- The reference variable can be created referencing to pointer variable.
o E.g: char *ch = “C++”;
char *&p = h;
CSE/C++/Module-I/Trilochan Rout/Lecture: 7, 8, 9 9

- A variable can contain various references modifying the value of one of


them results in a change in all other.
- Array of references is not allowed.
- Major application of this is, in passing arguments to function.
o Example:
void func(int &x) //int &x=m;
{
x = x +20; //x is incremented, so also is m.
}
void main( )
{
int m = 10;
func(m);
}
Example:
#include<iostream.h>
void main( )
{
int qty = 10;
int &qt = qty;
cout<<”qty = “<<qty<<”location = “<<&qty;
cout<<”\tqt = “<<qt<<\tlocation = “<<&qt;
qt++;
}
Output:

Scope Resolution(::) Operator:


CSE/C++/Module-I/Trilochan Rout/Lecture: 7, 8, 9 10

- It is used to access global value of the variable.

- This operator (::) allows a programmer to access a global variable name even
if it is hidden by a local re-declaration of the same variable.
- It allows to access global version of the variable.

Syntax:
:: variable name

#include<iostream>
Using namespace std;

int x=100;//global variable

int z=45;

Int main()
{

int x=50;// local variable


int k=55;
cout<<x;
cout<<x;
cout<<x;
cout<<::x;
cout<<k; // 55
cout<<z; //45

Output:
50
50
50
100
55

Example:
#include<iostream>
CSE/C++/Module-I/Trilochan Rout/Lecture: 7, 8, 9 11

Using namespace std;

int k = 101; //global variable k

int main()
{

Cout<<::k;// 101
int k = 50; //k local to main
{
int x = k;
int k = 75; //local to inner block

cout<<" X = "<<x<<endl;//50
cout<<" K = "<<k<<endl;//75
cout<<" :: K = "<<::k<<endl;//101
}
cout<<" K = "<<k<<endl;//50
cout<<" ::K = "<<::k<<endl;//101
return 0;

Output:

NB:
- It is applicable if the local and global variable having same name and
datatype.

 Member dereferencing Operator:


CSE/C++/Module-I/Trilochan Rout/Lecture: 7, 8, 9 12

- C++ permits us to access the class members through pointers. For this it
provides a set of three pointer-to-member operators.
I. :: * → to declare a pointer to a member of a class.
II. . * → to access a member using object name and a pointer to that
members.
III. →* : to access a member using a pointer to the object and a pointer to
that member

 Memory management operators in C++:


- Like C, C++ also support malloc( ), calloc( ), realloc( ) for
dynamic memory allocation and free( ) to release the
allocated space.
- Along with these functions, C++ provides us two operators
to perform memory management tasks.
o new → Allocate memory for object
o new[ ]→ Allocate memory for array
o delete→De-allocate memory for object
o delete[ ]→De-allocate memory for array

new and delete


new
delete

I. new operator:
- An object can be created using new operator as follows:
Syntax:
pointer_ var_name = new
datatype ;
Int *p;
P=new datatype;

- The new operator allocates sufficient memory to hold a data object of types
<datatype> and returns the starting address of the object to the pointer
variable.
CSE/C++/Module-I/Trilochan Rout/Lecture: 7, 8, 9 13

Example:
int *p;
float *q;
p = new int;
q = new float;

//alternative ways of declaration:


int *p = new int;
float *q = new float;

//initialization ways:
*p = 50;
*q = 75.25;
- Or, we can initialize the memory using new operator
Syntax:
pointer_name var_name = new datatype
(value) ;
Example:
int *p = new int(50);
float *q = new float(75.25);

- The new operator can be used to create memory space for user
defined datatype such as arrays, structures, classes, etc.

Syntax:
pointer_name var_name = new datatype
[size] ;

- Here, size specifies the number of elements in array.


CSE/C++/Module-I/Trilochan Rout/Lecture: 7, 8, 9 14

Example:

int *p = new int[5]; // create an array of 5 elements


with p[0]
as the 1st element
- For multi-dimensional arrays it is required to specify the entire
dimension.
Example:
int *ptr = new int[2][3]; //valid statement
int *ptr = new int[ ][3]; //valid statement
int *ptr = new int[2][]/[ ][ ]; //in-valid
statement
int *ptr = new int[r][3]; //valid statement

- The 1st dimension may be a variable whose value is supplied at


runtime. All others must be constant.

II. delete operator:


- The delete operator frees the memory allocated by the new operator.
- It is used when the object is used no longer needed and releases the
memory space.
Syntax:
delete pointer
variable;
// Size gives the number of elements to be
delete [size] pointer free
variable;
// delete the entire array
delete [ ] pointer
variable;

Example:
delete p;
delete q;
delete [5] p;
delete [ ] p;

NB:
- A data object is created inside a block with new operator, will remain in
existence until it is explicitly destroyed by using delete operator.
- If sufficient memory is not available, then the new operator returns a
NULL pointer.
CSE/C++/Module-I/Trilochan Rout/Lecture: 7, 8, 9 15

Important: The advantages of new operators over malloc ( ) and calloc( )


function:
1. new operator itself calculates the size of object without the use of sizeof( )
operator.
2. It automatically returns the correct pointer type, so type casting is not
required.
3. In new operator, allocation of memory and initialization of object can be
done at once.
4. new and delete operator has easier syntax and can be overloaded.
5. By using new operator, we can increase or decrease the size according to
the user requirements. Hence no memory waistage can be done and
memory can be released using delete operator after operation.
 Manipulators:
- Manipulators are operators that are used to format the data display.
- The most commonly used manipulators are
o endl
o setw
a) endl operator (line feed operator):
 When endl operator is used in an output statement causes a line feed to
be inserted.
 It has the same effect as that of “\n”.

Example:
cout<< “a = ”<<150<<endl
<<”b = ”<<20<<endl
<<”c = “<<1025<<endl;
Output:

a
1 5 0
= All are left justified
b
2 0
=
c
1 0 2 5
=

b) setw operator (line feed operator):


 The operator setw (width) specify a field width equal to size for printing
the values of variable and this value is right justified within the field.
Example:
cout<<setw(5)<<“sum =”<< sum<<endl; {where sum = 1105}

Output:

sum Right justified


1 1 0 5
=

 Comma and semicolon Operator:


- In C & C++, all statements must terminate with a semicolon ( ; ).
- In C++, it allows us to terminate a statement using comma operator after
satisfying the following rules:
CSE/C++/Module-I/Trilochan Rout/Lecture: 7, 8, 9 16

i. The variable declaration statement should be terminated with


semicolon (;).
ii. The statements followed by declaration statements like clrscr( ), cin,
cout, getch() can be terminated by using comma operator (;).
iii. The initialization of previously declared variable can be terminated
with comma.
iv. Last statement must be terminated with semicolon.
CSE/C++/Module-I/Trilochan Rout/Lecture: 7, 8, 9 17

Example:
void main()
{
int x;
clrscr();
x = 10;
cout<<”\n X = “<<x;
cout<<”\n”;
getch();
}

Output:
X = 10
 Some Operators that cannot be overloaded:
o sizeof operator
o . → Member access operator
o .* → ptr-to-member operator
o :: → Scope resolution operator
o ?: → Conditional operator

You might also like