3

CHAPTER

C++ Declarations

C
H
A
P
T
E
R

O
U
T
L
I
N
E
—•  3.1 Introduction
—•  3.2 Parts of C++ Program
—•  3.3 Types of Tokens
—•  3.4 Keywords
—•  3.5 Identifiers
—•  3.6 Dynamic Initialization
—•  3.7 Data Types in C++
—•  3.8 Basic Data Type
—•  3.9 Derived Data Type
—•  3.10 User-Defined Data Type
—•  3.11 The void Data Type
—•  3.12 Type Modifiers
—•  3.13 Wrapping Around
—•  3.14 Typecasting
—•  3.15 Constants
—•  3.16 Constant Pointers
—•  3.17 Operators in C and C++
—•  3.18 Precedence of Operators in C++
—•  3.19 Referencing (&) and Dereferencing (*) Operators
—•  3.20 Scope Access Operator
—•  3.21 Memory Management Operators
—•  3.22 Comma Operator
—•  3.23 Comma in Place of Curly Braces

3.1 INTRODUCTION

Before writing any program it is necessary to know the rules of syntaxes of the language. This enables a programmer to write error-free programs. The user makes many mistakes if he/she does not know the rules of the language even though the logic is clear. Thus the user fails to write programs due to poor knowledge of basic concepts.

Some basic concepts of C++ language are illustrated in this chapter to help the programmer develop the programs. As object-oriented programming is a new technology, the programmer will find a notable amount of new concepts to learn and master in it. This chapter explores syntaxes, data types, keywords etc.

Most of the C++ programmers are former C programmers. Some rules and regulations of C programs are valid in C++ also. Infact C++ is upward compatible to C. Hence the programs with C can be executed with C++. In C++, various improvements are done such as variable declaration is allowed anywhere in the program, new operators such as reference, scope access operator etc. are introduced and so on. All these concepts are illustrated ahead with figures and examples.

3.2 PARTS OF C++ PROGRAM

A Program consists of different sections as shown in Fig. 3.1. Some of them are optional and can be excluded from the program if not required. For example, every C and C++ program starts with function main( ), and if the user writes a program without main( ), it won't be executed. Hence, it is compulsory to write the main( ) function. In C, the structure allows to combine only variables of different data types. In addition, C++ allows combining variable and functions in structures and classes. The structure and classes are same and used for the same purpose. Functions can be defined inside or outside the class.

images

Fig.3.1 Parts of C++ program

(1) Include Files Section

Like C, C++ program also depends upon some header files for function definition. Each header file has an extension.h. The file should be included using # include directive as per the format given below

Example: # include <iostream.h> or # include “iostream.h .”

In this example <iostream.h> file is included. All the definitions and prototypes of function defined in this file are available in the current program. This header file also gets compiled with the original program. The header files are included at the top of the program so that they can be accessible from any part of the program. The user can also include them inside the program, but it is a good practice to include header files at the top of the program.

(2) Class Declaration or Definition

Declaration of a class is done in this section. It is also possible to declare class after the function main( ), but it is better to declare it before main( ) function. A class contains data variables, function prototypes or function definitions. The class definition is always terminated by a semi-colon. Function prototype declaration reports to the compiler it's name, return type and required argument list of the function. The function definition tells the compiler how the function works.

Example: float sum(float, float);

In the above example, the sum( ) function performs addition of two float numbers and returns float value.

(3) Class Function Definitions

This part contains definition of functions. The function definition can be done outside or inside the class. The functions defined inside the class are implemented as inline functions. The inline mechanism is illustrated in Chapter 5, “Functions in C++”. When a function is large, it is defined outside the class. In this case, prototype of a function is declared inside the class. Chapter 6, “Classes and Objects” illustrates these concepts.

(4) The main( ) Function

Like C, C++ programs always start execution from main( ) function. Thus execution of every program in C++ starts with main( ) function.

3.3 TYPES OF TOKENS

The C++ programs contain various components. The compiler identifies them as tokens. Tokens are classified in the following types. Figure 3.2 also indicates types of tokens.

(a) Keywords

(b) Variables

(c) Constants

(d) Special character

(e) Operators

images

Fig.3.2 Types of tokens

The keywords are reserved set of words with fixed meanings. The variables are used to hold data temporarily. The operators are used to perform different operations such as arithmetic, logical etc. The values such as 1, 5, 2.5 etc. are known as constants. The operators such as #, and ~ are known as special characters. The # is used for preprocessor directive, ? is a conditional operator and ~ is used for bitwise operation. The detailed descriptions of these tokens are described in sections ahead.

3.4 KEYWORDS

The C++ keywords are reserved words by the compiler and have fixed meanings. All C keywords are valid in C++. There are 63 keywords in C++. In addition, Turbo C++ permits 14 extra keywords as described in Table 3.4. The programmer may not apply them in the programs for defining variable names. However, few C++ compilers permit to declare variable names that exactly match to the keywords.

The common keywords between C and C++ are listed in Table 3.1. Table 3.2 describes the additional keywords of C++. These keywords are used with classes, templates, and exception handling etc. Table 3.3 contains keywords added by the ANSI committee. Table 3.4 contains additional keywords provided by Turbo C++ compiler.

3.5 IDENTIFIERS

Identifiers are names of variables, functions, and arrays etc. They are user-defined names, consisting of a sequence of letters and digits, with a letter as a first character. Lower case letters are preferred. However, the upper case letters are also permitted. The ( _ ) underscore symbol can be used as an identifier. In general, underscore is used to link two words in long identifiers. ANSI C++ restricts no bound on length of variables.

Table 3.1 C and C++ common keywords

images

Table 3.2 Additional C++ keywords

asm                               private
catch protected
class public
delete template
friend this
inline throw
new try
operator virtual

Table 3.3 Keywords added by ANSI committee

images

Table 3.4 Additional Keywords in Turbo C+ +

images

(1) The identifier name must begin with a character and should not start with a digit. There should not be any space between the characters in the variable but underscore is allowed.

(2) The identifier name should not be a C++ keyword.

(3) The identifier name may be a combination of upper and lower characters. For example, the variables suM, sum and Sum are not the same.

(1) Variable Declaration and Initialization

Variable    A variable is used to store values. Every variable has memory location. The memory locations are used to store the values of the variables. The variables can be of any type. It may be integer, char, float etc. The variable can hold single value at a time of its type. The values of variable varies i.e., the integer variable may contain values 2,6,33 and so on. The programmer can change contents of the variable. Thus, the identifier that holds varying values is called variables.

Variable Declaration    In C, all the variables must be declared in the declaration part. Hence, every time if one needs to declare a variable, the programmer must go back to the beginning of the program.

C++ permits declaration of variables anywhere in the program. This makes the programmer more comfortable to declare the variables and need not go to the beginning of the program. The declaration of variable consists of name of data type and variable list as follows:

Syntax:

(a) Data-type v;

(b) Data-type v1,v2…vn;

The programmer should declare data type explicitly before variable name. The data type tells the compiler about the type of data that is allowed to store in the variable. The identifier v is a variable. The statement (a) declares only one variable. The programmer can also declare more than one variable in a single statement as per statement (b).

Example:

(a) int a;

(b) float c,d,e;

In example (a), a is a variable of integer type. Example (b) declares variable c, d, and e of float type.

The statement (b) declares three variables in a single statement. The variable c is created first followed by d and e. The creation of variable takes place from left to right as shown in Figure 3.3. Each variable has a unique memory location.

In Figure 3.3 float is a data type and c,d and e are variables. The variable c is created first, followed by d and e. The direction of creation is from left to right. The extreme left variable is created first and the extreme right variable is created in the end.

images

Fig.3.3 Variable declarations

3.1 Write a program to read two integers through the keyboard. Declare the variables in C++ style.

# include <iostream.h>
# include <conio.h>
main ( )
{
   clrscr( );
   cout <<"Enter Two numbers : ";
   int num;
   cin >>num;
   int numl;
   cin > >num1;
   cout <<"Entered Numbers are : ";
   cout <<num<<"	"<<num1;
   return 0;
}

OUTPUT:

Enter Two numbers : 8 9
Entered Numbers are : 8 9

Explanation: In the above program, the variables num and num1 are declared inside the program and not at the beginning of the program. After declaration they are used with cin statement. The cin statement reads two integers and stores them in the variables num and numl. The cout statement displays entered values on the screen.

Initialization   When a variable is declared, appropriate number of bytes are reserved for it in the random access memory. The bytes are filled with garbage value if the user does not assign them a value. If the user performs operations without initializing a variable, the result will be unexpected. Hence, before using the variable it is essential to initialize them. Assigning a value to the variable is called as initialization. When a value is assigned to the variable, the garbage value is removed and replaced with the given value. The declaration of variable is done only once but initialization of variable can be done for any number of times. When a new value is assigned to a variable, its previous value is replaced with a new one.

Example:

int x;

Here, integer variable x is declared and not initialized. When the variables are not initialized, they are neither initialized to zero by the compiler nor they remain empty. The variables contain garbage values. The user cannot predict the garbage value since it is system dependent. The garbage values can be different on different systems.

If you try to print the value of x, the statement printf(“%d”,x) will display the garbage value (-29281 on my system). The cout <<x will display the value 0. If you use both these statements one after another, the value displayed will be 0.

3.2 Write a program to display value of uninitialized variable using cout statement.

# include <iostream.h>
# include <conio.h>
 
void main( )
{
   clrscr( );
   int x;
   cout<<x<<endl;
   cout<<x+5<<endl;
   cout<<5+(++x);
}

OUTPUT
0
5
6

Explanation:  In the above program, the first cout statement displays the value of x to be zero. The second statement displays the value 5. The third statement displays the value 6. In the third statement, x is incremented first and then added to 5. This program is compiled under compact memory model. If this program is compiled and executed under any other memory models, the result will be garbage.

All the operations performed in the above program are directly put in the cout statement. If the above program is executed with the printf( ) statement, the program will display the garbage values.

The following program displays garbage value of the variable:

3.3 Write a program to display garbage value of a variable.

# include <iostream.h>
# include <conio.h>
# include <stdio.h>
void main ( )
{
   int x,y;
   clrscr( );
   y=5+(++x);
   cout<<"Value of Y : "<<y;?
}

OUTPUT
Value of Y : 1134

Explanation:  In the above program, 5 is added to variable x and assigned to y. One may expect that the value of y will be 6. Here, the value of y displayed is a garbage value. From the above program it is clear that if the variable is not initialized, it will be assigned a garbage value.

In the last program, the statement y = 5 + (++ x); uses variable x and y. The variable x and y are not initialized. The variable y has no effect on the operation because it is at the left side and the result of expression of right side is assigned to it. The variable x holds garbage value. Integer 5 is added to garbage value of x and stored in the variable y. Hence the value of y displayed is 1134.

Initialization of variable can be done at the place where they are declared or anywhere in the program before their use. The variable can be initialized using assignment operator or input statement such as cin, get( ) etc.

Figure 3.4 indicates the syntax and example of initialization of variable.

images

Fig.3.4 Initialization of variables

Syntax:

data-type variable_name = value;

Example:

int k=5;

In the above example, variable k of integer type is declared. The value 5 is stored in it.

int a,b,c,d;

a=b=c=d=5;

In the above example, all the variables a, b, c and d are initialized to 5. An example is illustrated below.

3.4 Write a program to initialize more than one variable at a time.

# include <conio.h>
# include <iostream.h>
void main( )
{
   int a,b,c,d;
   a=b=c=d=5;
   clrscr( );
   cout <<"
 a="<<a <<" b="<<b <<" c="<<c <<" d="<<d;
}

OUTPUT
a=5 b=5 c=5 d=5

Explanation: In the above program, variables a, b, c and d are declared. In the next statement the entire four variables are initialized with 5. The value 5 is first assigned to variable d then the value of d is assigned to c, c is assigned to b and finally b is assigned to a. Figure 3.5 simulates this assignment.

images

Fig.3.5 Initialization of variables

3.5 Write a program to prove that a variable can be initialized for more than one time.

#include<iostream.h>
#include<conio.h>
void main( )
{
   clrscr( );
   int x=10;
   cout <<"
 x= "<<x;
   x=30;
   cout<<"
 x= "<<x;
}

OUTPUT

x= 10
x= 30

Explanation: In the above program, integer variable x is declared and initialized with 10. The cout statement displays the value of x on the screen. Again the variable x is initialized with 30. The previous value 10 is replaced with 30. The second cout statement displays the value of x equal to 30.

3.6 DYNAMIC INITIALIZATION

The declaration and initialization of variable in a single statement at any place in the program is called as dynamic initialization. The dynamic initialization is always accomplished at run-time i.e., when program execution is in action. Dynamic means process carried out at run-time, for example, dynamic initialization, dynamic memory allocation etc. The C++ compiler allows declaration and initialization of variables at any place in the program. In C, initialization of variables can be done at any place but the variable must be declared at the beginning of the program as illustrated in the following program:

3.6 Write a program in C to demonstrate declaration and initialization of a variable.

# include <conio.h>
# include <stdio.h>
void main( )
{
   int r;
   float area;
   clrscr( );
   printf ("
 Enter radius : ");
   scanf ("%d",&r);
   area=3.14*r*r;
   printf ("
 Area =%g",area);
}

OUTPUT

Enter radius : 4
Area =50.24

Explanation: The above program is executed with C compiler. In this program, the variables area and r are declared at the beginning because in C, declaration is compulsorily done at the beginning. The multiplication of 3.14 and variable r is assigned to variable area. This assignment is done inside the program. The above program demonstrates that in C, variable declaration is done at the beginning and initialization can be done at any place in the program.

3.7 Write a program in C++ to demonstrate dynamic initialization.

# include <conio.h>
# include <iostream.h>
void main( )
{
   clrscr( );
   cout<<"
 Enter radius : ";
   int r;
   cin>>r;
   float area=3.14*r*r;
   cout <<"
 Area ="<<area;
}

OUTPUT

Enter radius : 3
Area =28.26

Explanation: In program 3.7, the variable r and area are declared inside the program. The declaration and initialization of a variable area is done in single statement inside the program. Consider the following statement:

float area=3.14*r*r;

In the above statement float variable area is declared and product of 3.14*r*r is assigned to area. The assignment is carried out at run-time. Such type of declaration and initialization of a variable is called as dynamic initialization.

3.8 Write a program to calculate the length of string. Use run-time declaration and initialization of variables.

# include <iostream.h>
# include <string.h>
# include <conio.h>
main( )
{
   clrscr( );
   char name[15];
   cout <<"Enter Your Name :";
   cin >>name;
   int len=strlen(name);
   cout <<"The length of the string is :"<<len;
   return 0;
}

OUTPUT:

Enter Your Name : Santosh
The length of the string is :7

Explanation: In the above program, the cin statement reads the string through the keyboard. The strlen( ) function is used to determine the length of the given string. The strlen( ) function calculates the length of the string and returns the length to variable len. The variable len is declared and value returned by strlen( ) is assigned to variable len. To avoid separate statements for declarations and initializations, both statements are combined in one statement. Declaration and initialization has been carried out in one statement int len=strlen(name).

3.7 DATA TYPES IN C++

Data is a collection of characters, digits, symbols etc. It is used to represent information. The data are classified in various types. Figure 3.6 indicates all data types. C++ data types can be classified in the following categories:

(a) Basic data type

(b) Derived type

(c) User-defined type

(d) Void data type

images

Fig.3.6 C++ data types

3.8 BASIC DATA TYPE

The basic data types supported by C++ are described with their size in bytes and ranges in Table 3.5. Figure 3.7 shows data types and their sizes.

Table 3.5 Basic data types supported by C++ with size and range

 

DATA TYPE SIZE IN BYTES RANGE
char 1 -128 to 127
unsigned char 1 0 to 255
signed char 1 -128 to 127
int 2 -32768 to 32767
unsigned int 2 0 to 65535
signed int 2 -32768 to 32767
short int 2 -32768 to 32767
unsigned short int 2 0 to 65535
signed short int 2 -32768 to 32767
long int 4 -2147483648 to 2147483647
signed long int 4 -2147483648 to 2147483647
unsigned long int 4 0 to 4294967295
float 4 3.4E-38 to 3.4E+38
double 8 1.7E –308 to 1.7E+308
long double 10 3.4E –4932 to 1.1E +4932
enum 2 -32768 to 32767
bool 1 true / false

3.9 DERIVED DATA TYPE

The derived data types are of following types:

(1) POINTERS

(2) FUNCTIONS

(3) ARRAYS

(4) REFERENCES

images

Fig.3.7 Data types and their sizes

(1) Pointers

A pointer is a memory variable that stores a memory address. Pointer can have any name that is legal for other variable and it is declared in the same fashion like other variable but it is always denoted by ‘*’ operator.

int *x;

float *f;

char *y;

In the first statement ‘x’ is an integer pointer and it tells to the compiler that it holds the address of any integer variable. In the same way f is a float pointer that stores the address of any float variable and ‘y’ is a character pointer that stores the address of any character variable.

3.9 Write a program to use pointers.

# include <conio.h>
# include <iostream.h>
 
void main( )
{
   clrscr( );
   int x=2,*p;
   cout <<"
 Address of x = "<<(unsigned)&x;
   p=&x;
   cout <<"
 Value of x ="<<*p;
}

OUTPUT

Address of x = 4096
Value of x=2

Explanation: In program 3.9, x is an integer variable and *p is an integer pointer. The first cout statement displays the address of variable x. The address of x is assigned to pointer p. The pointer variables are always used to store address of another variable. The second statement displays the value of x using pointer p. Figure 3.8 explains pointers.

(2) Functions

A function is a self-contained block or a sub-program of one or more statements that perform a special task when called. The C++ functions are more civilized than C. It is possible to use the same name with multiple definitions called as function overloading. Figure 3.9 illustrates the function. In Figure 3.9 funA( ) and funB( ) are two user-defined functions. These are invoked from the body of main. After execution of the funA( ) and funB( ) the program control returns back to the calling function main( ).

images

Fig.3.8 Pointers

images

Fig.3.9 Functionsx

A simple program on function is described below.

3.10 Write a program to demonstrate user-defined functions.

# include <conio.h>
# include <iostream.h>
 
void main( )
{
   clrscr( );
   void show(void);
   show( );
}
 
void show( )
{
   cout <<"
 In function show( )";
}

OUTPUT

In function show ( )

Explanation: In the above program, the function show( ) is defined. The function body contains only one cout statement. When the function is executed, a message is displayed. For more details of functions refer to chapter 5 “Functions in C++”.

(3) Arrays

Array is a collection of elements of similar data types in which each element is located in separate memory location. For example,

int b[4];

The above statement declares an array b[] which can hold four integer values. The following program illustrates use of array.

3.11 Write a program to declare, initialize an array. Display the elements of an array with their addresses.

# include <conio.h>
# include <iostream.h>
void main( )
{
clrscr( );
int b[4]={2,4,3,7};
 
cout <<"b[0] Value = "<<b[0]<<" Address : "<<(unsigned)&b[0]<<endl;
cout <<"b[1] Value = "<<b[1]<<" Address : "<<(unsigned)&b[1]<<endl;
cout <<"b[2] Value = "<<b[2]<<" Address : "<<(unsigned)&b[2]<<endl;
cout <<"b[3] Value = "<<b[3]<<" Address : "<<(unsigned)&b[3]<<endl;
}

OUTPUT
b[0] Value = 2 Address : 4090
b[1] Value = 4 Address : 4092
b[2] Value = 3 Address : 4094
b[3] Value = 7 Address : 4096

Explanation: In the above program, an array b[4] is declared and initialized. The cout statement displays the array elements with their addresses. The b[0] refers to first element; b[1] refers to second element and so on. Figure 3.10 shows element numbers, elements and addresses.

images

Fig. 3.10 Array elements in memory

(4) References

C++ reference types, declared with & operator are nearly identical but not exactly same to pointer types. They declare aliases for object variables and allow the programmer to use variable by reference. This reference type is illustrated in section 3.20.

3.10 USER-DEFINED DATA TYPE

User-defined data types are of the following types:

(1) Structures and classes

(2) Union

(3) Enumerated data type

(1) Structure and Classes

Keyword struct

The struct is a keyword and used to combine variables of different data types into a single record.

Syntax:

struct[< struct name >
{
<data-type> <variable-name1, variable-name, 2 > ; 
<data-type> <variable-name3, variable-name, 4>;

} <structure variable declarations>;

struct name : An optional tag name that defines the structure type.

structure variables : These are member variables and hold data.

Though struct name and structure variables are noncompulsory, one of them should be present. Member variables in the structure are declared by naming a <data-type>, followed by one or more <variable-name> separated by commas. A semicolon can separate variables of different data types.

Example:

struct my_friend
{
   char fname [80], phone[80];
   int age, height;
} friendA ;

The structure my_friend defines a variable containing two strings (fname and phone) and two integers (age and height) as shown in Fig. 3.11. To access elements in a structure, we use a record selector (.) called as dot operator. For example,

strcpy(friend.fname,”Sachin”);

images

Fig.3.11 Structure and its elements

3.12 Write a program to declare struct object, initialize it and display the contents.

#include<iostream.h>
#include<conio.h>
void main( )
{
   clrscr( );
 
   struct my_friend
{
   char *fname;
   int phone, age, height;
 } A ;
      A.fname="Bharat";
      A.phone=26251;
      A.age=22;
      A.height=4.5;
   cout <<"
 Contents of object A";
   cout <<"
Name : "<<A.fname;
   cout <<"
Phone : "<<A.phone;
   cout <<"
Age : "<<A.age;
   cout <<"
Height : "<<A.height;
}

OUTPUT
Contents of object A
Name : Bharat
Phone : 26251
Age : 22
Height : 4

Explanation: In the above program, struct my_friend is defined with four member variables. Identifier A is an object of struct my_friend. The initialization of data members of struct is done using dot operator with object A. The cout statements display contents of object A.

Keyword class

The class is a new keyword introduced in C++. It's use is same as struct keyword. Example on classes are explained in chapter 6, Classes and Objects. To declare a class following syntax is used:

Syntax:

<classkeyword> <class- name> [<:baseclasslist>]
{<member variable list>}

Class keyword: It is one of the keywords class, struct, or union.

Class-name: It can be any unique name inside its scope.

Baseclasslist: If the class is derived class, then it follows the list of the base class (es). It is optional.

Member variable list: Defines the data member variables and member functions.

Example:

class circle 		 
{ 		 
   int radius;		// data member 	 
   int area (void); 	// member function 	 
}; 		 

(2) Union

A union is same as compared to a struct, the only difference is that it lets the user to declare variables that share same memory space.

Syntax:

union [<union name>] 	 
{ 	 
<data-type> <variable names>;
} [<union variables name>];

Example:

union charorint
{
   char c;
   int i;
} number;

C++ will allocate sufficient storage in union variable number to hold the big element in the union. The union member variable number.c and number.i uses the same memory location in memory. In this way, writing into one will replace the other. Member variables of a union are accessed in the same way as a struct.

Anonymous Unions An anonymous union does not contain tag name. Elements of such union can be accessed without using tag name. Consider the following example:

union
{
   int k;
   float j;
};

Both the member variables of union have the same memory location. They can be accessed as per the following:

k=20;
j =2.2;

The declaration should not declare a variable of the above union type. Following program illustrates the use of anonymous union:

3.13 Write a program to declare anonymous union and access its elements.

# include <stdio.h> 	 
# include <iostream.h> 	 
# include <conio.h>
  	 
main( ) 	 
{ 		 
   clrscr( ); 	 
   union 	 
{ 		 
       int k; 	 
       float  f; 
};
f=3.1;
k=2; 
 	 
cout <<"
 k = "<<k;
printf ("
 f = %.1f",f);
return 0;
} 	 

OUTPUT
k = 2
f = 3.1

Explanation: In program 3.13, anonymous union is declared. The union has two data member variables, k as integer variable and f as a float variable. The union has no tag name; hence it is called as anonymous union. The member variable of such a union can be accessed directly like normal variable. Both the variables hold the same memory location.

(3) Enumarated Data Type

The enum is a keyword. It is used for declaring enumeration data types. The programmer can declare new data type and define the variables of these data types that can hold. For example, the user can define the material as new data type. It's variable may be solid, liquid or gas. Thus three values are restricted for this new data type. These enumeration data types are useful in switch( ) case statement.

The syntax for enumerated data type is given below. It uses a keyword enum.

  enum logical { false,true};
  enum logical {true=2, false=4};
  enum components{solid,liquid,gas};

This statement declares a user-defined data type. The keyword enum is followed by the tag name logical. The enumerators are the identifiers false and true. Their values are constant unsigned integers and start from 0. The identifier false refers to 0 and true to 1. The identifiers are not to be enclosed with quotation marks. Please also note that integer constants are also not permitted. We can also start the constants as given in the second statement. In the second statement true refers to 2 and false refers to 4. In the third statement, the component is the user-defined data type and the variables attached to it are solid, liquid and gas.

The ANSI C++ and Turbo C++ allow us to declare variables of enum type.

logical =N   // N is of the type logical
logical F=false		// valid
logical  TT=1		// invalid in c++ 	 
logical TT=(logical) 1	// valid 	 
int k=true;		// valid 	 

We can also define enum without tag name. Consider the following example:

enum{yes, no};

Here, yes is 0 and no is 1 and can be used as int answer=yes.

3.14 Write a program to declare enum data type and display their values.

# include <iostream.h> 	 
#include <conio.h> 	 
void main( ) 	 
{ 	 
       clrscr( ); 	 
       enum logical {false,true}; 	 
       cout <<"true : "<<true <<" false : "<<false; 	 
} 

OUTPUT
true : 1 false : 0

Explanation: In program 3.14, enum data type logical is declared with two values i.e. false and true. The false contains value 0 and true contains the value 1. The cout statement displays the contents of true and false. True means 1 and false 0.

3.11 THE void DATA TYPE

The void type is added in ANSI C. It is also known as Empty data type. It can be used in two ways.

(a) When specified as a function return type, void means that the function does not return a value.

void message(char *name)
{
printf("Hello, %s.", name);
}

Here, message( ) is a void function. The keyword void is preceded by the function name. This function when executed displays only message and does not return any value to the calling function.

(b) The void keyword is also used as argument for function. When found in a function heading, void means that the function does not take any arguments.

int fun(void)
{
return 1;
}

Here, the function fun( ) does not require any argument. It returns an integer value.

(c) When specified as a function return type and in function heading i.e., the function neither returns a value nor requires any argument.

void fun(void);

The above function neither returns a value nor requires any argument.

3.12 TYPE MODIFIERS

The keywords signed, unsigned, short, and long are type modifiers. A type modifier changes the meaning of the base data type to produce a new data type. Each of these type modifiers is applicable to the base type int . The modifiers signed and unsigned are also applicable to the base type char. In addition, long can be applied to double data type. When the base type is absent from a declaration, int is supposed.

Examples:

long		  l; 	// int is implied 	 
unsigned char c; 			 
signed int	  s; 	// signed is default 	 
unsigned long int u; 	//  int OK, not necessary 	 

3.15 Write a program to declare variable with type modifiers, initialize them and display their contents.

# include <conio.h> 	 
# include <iostream.h> 	 
 
void main( ) 	 
{ 	 
      clrscr( ); 	 
      short t=1; 	 
      long k=54111; 	 
      unsigned u=10; 	 
      signed j=-10; 	 
 
      cout <<"
 t="<<t; 	 
      cout <<"
 k="<<k; 	 
      cout <<"
 u="<<u; 	 
      cout <<"
 j="<<j; 	 
}

OUTPUT
t=1
k=54111
u=10
j=-10

Explanation: In the above program, variables t, k, u, and j are declared. When the variable is declared with the keyword short or signed, it is of type short-signed integer. The long type of variable can store large integer. The unsigned type of variable can store only positive values upto 65535.

3.13 WRAPPING AROUND

When a variable contains a value, which goes over the range provided by compiler, the compiler won't flag any error in such cases and wrapping around takes places. For example, the range of unsigned integer is 0 to 65535. Negative values and values greater than 65535 are not permitted. If the variable of this type is assigned a value that is not in the above range, wrapping takes place as shown in Fig. 3.12.

Unsigned int x=65536;

In the above statement, the unsigned variable x is assigned a value 65536 which is greater by one than the range. In this case, difference between assigned value and total numbers that comes under range are considered. For example, the total number that comes under this range is 65536 (0 to 65535). The value assigned is 65536. The difference is zero (65536-65536). The x contains 0. The same rule is applied to all other basic data type.

images

Fig.3.12 Value wrapping around

3.16 Write a program to demonstrate wrapping around with unsigned integer.

# include <conio.h> 	 
# include <iostream.h> 	 
 
void main( ) 	 
{ 	 
   clrscr( ); 	 
   unsigned int x=65536; 	 
   cout <<" x ="<<x; 	 
}

OUTPUT
x=0

Explanation: In the above program, unsigned integer variable x is declared and initialized with 65536. The value assigned is beyond the range. Hence, wrapping around takes place. The value of x displayed is zero.

3.17 Write a program to demonstrate wrapping around with unsigned integer variable.

# include <conio.h> 	 
# include <iostream.h> 	 
void main ( ) 	 
{ 	 
   clrscr( ); 	 
   unsigned int x=0; 	 
   --x; 	 
   cout <<"x ="<<x; 	 
   x+=2; 	 
   cout<<"
x ="<<x; 	 
} 	 

OUTPUT
x =65535
x =1

Explanation: In the above program, unsigned integer variable x contains value 0. The variable x is decremented. As unsigned integer never takes negative values, wrapping around takes place and x holds nearest positive value i.e., 65535. The variable is again incremented by two. In this case the value of x exceeds the limit and wrapping takes place. The value of x displayed is 1.

3.14 TYPECASTING

C/C++ supports data types such as integer, character, floating, double precision, floating point etc. Some of them are specified as int, short int, and long int. Typecasting is essential when the values of variables are to be converted from one type to another type. C++ allows implicit as well as explicit type conversion.

(1) Explicit Typecasting

Sometimes errors may be encountered in the program while using implicit typecasting. It is preferred to use explicit type conversion process. The desired type can be achieved by typecasting a value of particular type. The explicit type conversion is done using typecast operator. The compiler is instructed to do type conversion using typecast operator. The following are the syntaxes of typecasting in C and C++.

(data-type name) expression // C style syntax 	 
data-type name (expression) // C++ style syntax 	 

Examples:

x=(float)5/2; 	// C style 	 
x=5/float(2); 	// C++ style 	 

In the C style example, the target data type name is enclosed in parenthesis whereas in C++ style example, the argument is enclosed in parenthesis.

In the example (float) 5/2, the expression 5/2 is declared as float type. Hence, the result of expression turns to float type. Consider the given example.

float x;
x=(int) 5/2.0;

The above expression returns the value 2.5, even if an int typecast operator is used. The typecast operator attempts to make the expression int type, but the expression contains float type operand. Hence it is considered as float type expression and returns the result of float type.

x= int (5/2.0);

In the above example, the expression is enclosed in the parenthesis. The expression is solved first and the result obtained is used for typecasting. The expression 5/2.0 returns 2.5 and the typecast operator int converts it to integer.

3.18 Write a program to explain new style of typecasting in C++.

#include <iostream.h>
#include<constream.h>
 
void main( )
{
   clrscr( ); 	 
   cout<<(int)45.4;        // C style 	 
   cout<<"
"<<int(17.78); // C++ style 	 
}

OUTPUT
45
17

Explanation: In the above program, the float values are converted to integer type and then displayed. The compiler using the typecast operator int explicitly does the type conversion task.

The above example converts higher type to lower type data. The float type is converted to integer type. It is also possible to convert in reverse order i.e., integer to float. The example is illustrated below.

3.19 Write a program to covert float type data to integer. Use the syntaxes of both C and C++.

#include <iostream.h> 	 
#include<constream.h> 	 
void main ( ) 	 
{ 	 
   clrscr( ); 	 
   int a,b,c; 	 
   float x,y; 	 
   a=19; 	 
   b=10;
   c=3; 	 
   x=(float) a/c; // C style 	 
   cout <<"
 x="<<x; 	 
   y=float(b)/c; // C++ style 	 
   cout <<"
 y="<<y; 	 
   getche( ); 	 
} 		 

OUTPUT:
x=6.333333
y=3.333333

Explanation: In the above program, the integer values are converted to float type and the results are displayed as the output. The compiler using the typecast operator float explicitly does the type conversion task.

3.20 Write a program to show difference of typecasting between C and C++.

#include <iostream.h> 	 
#include<constream.h> 	 
void main( ) 	 
{ 	 
   clrscr( ); 	 
   float x,y; 	 
   x=(float) 5/2; // C style 	 
   cout <<"
 x="<<x; 	 
   y=float(9)/2; // C++ style 	 
   cout <<"
 y="<<y; 	 
} 

OUTPUT
x=2.5
y=4.5

Explanation: The above example uses typecasting methods of C and C++. The x and y are two float variables. The expression 5/2 is evaluated and before storing in variable x, the result obtained is converted to float. In C style, the target data type name is enclosed in parenthesis. In C++ style, one of the argument of expression is enclosed in parenthesis preceded by target data type name. The expression y=float (9)/2; can be written in the following ways and produces the same result:

y=float (9)/2;
y=9/float(2);

Here, the float keyword is a typecast operator. The typecast operator instructs the compiler explicitly to make type conversion.

(2) Implicit Type Conversion

The type conversion is carried out when the expression contains different types of data items. When the compiler carries such type conversion itself by using inbuilt data types in routines then it is called implicit type conversion. The variable of lower data (small range) type when converted to higher type (large range) is known as promotion. When the variable of higher type is converted to lower type, it is called as demotion. Table 3.6 describes various rules that a compiler follows.

Table 3.6 Implicit type conversion rules

 

Argument1
Argument 2
Output
char
int
int
double
int
long
int
int
float
long
float
double
double
unsigned
int
float
long
double
double
double
unsigned

3.21 Write a program to demonstrate implicit type conversion.

# include <iostream.h>
# include <conio.h>
 
void main( )
{
   clrscr( );
   int j=2.54;
   int k=’A’;
   char c=87.5;
   cout <<" j= "<<j;
   cout<<endl<<" k= "<<k;
   cout<<endl<<" c= "<<c;
}

OUTPUT
j= 2
k= 65
c= W

Explanation: The above program works as described in Table 3.7.

Table 3.7 Examples of implicit type conversion

 

Expression Output
int j=2.54 A float value is assigned to integer variable. Here, 2 is assigned to j and fractional part will get vanished.
int k=’A’; A char type value is assigned to integer variable. Here, ASCII value of ?' (65) is assigned to k. Here, char to int conversion takes place.
char c=87.5 A float value is assigned to char variable. Here, fractional part is ignored and W ASCII equivalent of 87 is assigned to variable c.

3.15 CONSTANTS

The constants in C++ are applicable to the values which do not change during execution of a program. C++ supports various types of constants including integers, characters, floating, and string constants. C++ has two types of constants; literal and symbolic.

(1) Literal Constant

A literal constant is directly assigned to a variable. Consider the following example:

int x=5 ;

where x is a variable of type int and 5 is a literal constant. We cannot use 5 to store another integer value and its value cannot be altered. The literal constant doesn't hold memory location. C++ supports literal constants as listed in Table 3.8 with examples.

Table 3.8 Literal constants

Example Constant type
542 Integer constant
35.254 Floating point constant
0x54 Hexadecimal integer constant
0171 Octal integer constant
‘C’ Character constant
“C plus plus” String constant
L “xy” Wide-character constant

(2) Symbolic Constant

A symbolic constant is defined in the same way as variable. However, after initialization of constants the assigned value cannot be altered.

The constant can be defined in the following three ways:

(1) # define

(2) The const keyword

(3) The enum keyword

(1) The # define preprocessor directive can be used for defining constants.

# define price 152

In the above example, price symbolic constant contains 152 and here it is not mentioned whether the type is int, float or char. Every time when the preprocessor finds the word price, substitutes it with 152.

(2) We can also define a constant using const keyword.

const int price=152;

The above declaration defines a constant of type int. Here, data type is strictly maintained while doing operation. The value of constant cannot be changed at run-time.

3.22 Write a program to define const variable using const keyword.

#include <iostream.h>
#include<constream.h>
 
void main( )
{
   clrscr( );
   const Sunday=0;
   const Monday=1;
   int c;
 
   cout <<"
 Enter day (0 or 1) :";
   cin>>c;
   if (c==Sunday && c!=Monday)
   cout<<"
 Holiday";
   else
   cout<<"
 Working day";
}

OUTPUT
Enter day (0 or 1) :0

Holiday

Explanation: In the above program, Sunday and Monday are constants initialized with 0 and 1. The data type name is not mentioned. In such case int type is considered. The user enters the choice either 0 or 1 and it is stored in the variable c. If condition statement compares the value of variable c with constants Sunday and Monday, one of the messages as given in the programs is displayed depending upon entered value.

(3) Constants can be defined using enumeration as given below:

Example:

enum {a, b,c};

Here, a, b and c are declared as integer constants with values 0, 1 and 2.

We can also assign new values to a, b and c.

enum [a=5,b=10,c=15};

Here, a, b and c are declared as integer constants with values 5, 10 and 15.

3.16 CONSTANT POINTERS

C++ allows us to create constant pointer and also pointer to constant. Consider the following example:

(1) Constant Pointer

It is not possible to modify the address of the constant pointer.

char * const str=”Constant”;

In the above example, it is not possible to modify the address of the pointer str. Thus, the operations like the following will generate error:

 // str="san"; 	// cannot modify a constant object	 
 // ++str; 	// cannot modify a constant object 	 

The following program won't work and will generate error message “cannot modify a constant object”.

# include <iostream.h> 	 
# include <constream.h> 	 
 
void main( ) 	 
{ 	 
clrscr( ); 	 
 
   char * const str="Constant"; 	 
   str="new constant"; 	 
   cout <<str; 	 
} 	 

(2) Pointer to Constant

If pointer is declared to constant, we can change the value by using actual variable that is not possible using pointer.

int const *pm=&k;

In the above example, pm is declared as pointer to constant. The operations given below are possible and invalid:

// k=5; 	// possible 	 
// *pm=5 	// cannot modify the constant object 	 
// pm++; 	// possible 	 
// ++ *pm; 	// cannot modify a constant object 	 
// *pm=5; 	// cannot modify a constant object 	 

3.23 Write a program to declare constant pointer. Modify the contents of the pointer.

# include <iostream.h> 	 
# include <constream.h> 	 
 
void main( ) 	 
{	 
   clrscr( );	 
   int k=10;	 
   int const *pm=&k;	 
   k=40; 	 
// *pm=20; // invalid operation	 
   cout<<*pm; 	 
} 	

OUTPUT
40

Explanation: In the above program, variable k is an integer pointer. The variable *pm is declared as constant integer pointer. The value of k cannot be changed through constant pointer because constants are fixed entity. Hence, operation such as *pm=5, *pm+ + are invalid operations. These operations attempt to change the contents of constant which is never possible. Changing the value of variable k can change the contents. The variable k is not constant but its pointer is constant. Hence, the constant pointer can be involved to modify the value.

(3) Pointer and Variable both Constants

const char * const p=”ABC”;

In the above example, both the pointer and variable are constants. Hence it is not possible to change the value and address of the pointer.

3.17 OPERATORS IN C AND C++

Operator is an instruction to the compiler or interpreter, specified by a single or double symbol to perform certain operations with constants. Different types of operators are shown in Fig. 3.13.

Example:

5+10

Here, 5 and 10 are constants. The symbol ‘+’ is an operator that indicates the operation to be performed and performs addition of numbers and is a single operator.

int x=5;
++x;

In the above example the operator ++ is an increment operator. This operator adds one to the value of operand. The different types of operators with their symbols are described in Table 3.9.

images

Fig. 3.13 Types of operators

Table 3.9 Types of operators

 

Types of Operators Symbolic Representation
Arithmetic Operators +, - , *, / and %
Relational Operators >,<,= = =,>=.<= and !=
Logical Operators &&, ¡I and !
Increment and Decrement Operators ++ and —
Assignment Operators =
Bitwise Operators &/ ! ,*,”,” and ~
Special Operators ,
Conditional Operators ? ;

C++ supports all the operators of C. C++ also introduces few new operators as listed in Table 3.10.

Table 3.10 Operators in C++

 

Operator Description
<< Insertion operator
>> Extraction operator
:: Scope access (or resolution) operator
::* Pointer to member decelerator
->* Deference pointers to pointers to class members
.* Deference pointers to class members
delete Memory release operator
New Memory allocation operator

The scope access (or resolution) operator :: (two semicolons) allows you to access a global (or file duration) name even if a local hides redecoration of that name. The .* and ->* operators are deference pointers to class members and pointers to pointers to class members. The insertion and extraction operator are used with cout and cin objects to perform I/O operations. The new and delete operators are used to allocate and de-allocate memory.

3.18 PRECEDENCE OF OPERATORS IN C++

C++ operators are classified into 16 groups as shown in Table 3.11. The #1 group has the first (highest) precedence, group #2 (Unary operators) takes second precedence, and so on to the Comma operator, which has lowest precedence.

The operators within each category have equal precedence.

The Unary (group #2), Conditional (group #14), and Assignment (group #15) operators associate right-to-left; all other operators associate left-to-right.

Table 3.11 Precedence of operators in C+ +

 

# Group Operator Operation
1. Top ( ) Function call
[] Array subscript
-> C++ indirect component selector
:: C++ scope access/resolution
. C++ direct component selector
2. Unary ! Logical negation (NOT)
~ Bitwise (1's) complement
+ Unary plus
- Unary minus
++ Pre-increment or post-increment
-- Pre-decrement or post-decrement
& Address
* Indirection
size of Returns size of operand, in bytes
new Dynamically allocates C++ storage
delete Dynamically de-allocates C++ storage
3. Multiplicative * Multiply
/ Divide
% Remainder (modulus)
4. Member Access .* C++ deference
->* C++ deference
5. Additive + Binary plus
- Binary minus
6. Shift << Shift left
>> Shift right
7. Relational < Less than
<= Less than or equal to
> Greater than
>= Greater than or equal to
8. Equality == Equal to
!= Not equal to
9. Bitwise & Bitwise AND
^ Bitwise XOR
| Bitwise OR
10. Logical && Logical AND
|| Logical OR
11. Conditional ?: (a ? x : y means “if a then x, else y”)
12. Assignment = Simple assignment
*= Assign product
/= Assign quotient
%= Assign remainder (modulus)
+= Assign sum
- = Assign difference
&= Assign bitwise AND
^= Assign bitwise XOR
|= Assign bitwise OR
<<= Assign left shift
>>= Assign right shift
13. Comma , Evaluate

Most of the operators in this table can be overloaded except the following:

. C++ direct component selector 	 
.* C++ deference 	 
:: C++ scope access/resolution 	 
?: Conditional 	 

Precedence of * and [ ] Operators

In C++, the statements * x[4] and (* x)[4] are not the same because the * operator has lower precedence than the [] operator. Consider the following examples:

(a) int *arr[5];

The above statement declares an array of five pointers and the following operation is invalid because the array name is itself an address and it is a constant. Hence, it cannot be changed.

    arr++;       or ++arr;

(b) int (* arr)[5]

The above declaration declares a pointer to an array of five elements. Hence the operations such as arr++ and ++arr are not supported. The following program explains both these points:

3.24 Write a program to declare a pointer to array and display the elements.

# include <iostream.h>
# include <conio.h>
void main( ) 	 
{ 	 
   void display(int [] [3],int); 	 
   clrscr( ); 	 
 
   int a[3][3]={ {11,22,33}, 	 
                 {44,55,66}, 	 
                  {77,88,99} 	 
                          }; 	 
   display (a,3); 	 
}
  	 
void display (int x[] [3], int k) 	 
{ 	 
   int (*d) [3]; 	 
   d=x; 	 
 
   for (int g=0;g<k;g++) 	 
   { 	 
       for (int h=0;h<3;h++) 	 
       cout <<d[g][h] <<"	"; 	 
 
       cout<<"
"; 	 
   } 	 
}

OUTPUT

11    22    33

44    55    66

77    88    99

Explanation: In the above program, an integer array a[3][3] is declared and initialized. The base address of array and number of rows are passed to function display( ). In function display( ), d is a pointer. The base address received by the variable x is assigned to pointer d. Using nested for loops, the elements of array are displayed.

3.19 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.

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.

qt=qt*2;

Now, contents of qt and qty will be 20.

Note that the token & is not an address operator. The declaration int & indicates reference to data type int.

PRINCIPLES FOR DECLARING REFERENCE VARIABLE

(1) A reference variable should be initialized.

(2) Once a reference variable is declared, it should not refer to any other variable. Once the actual variable and reference variable are connected they are tied jointly congenitally.

(3) The reference variable can be created referring to pointer variable. The declaration would be as given below:

      char * h="C++";
      char *&q=h;

(4) A variable can contain various references. Modifying the value of one of them results in a change in all others.

(5) Array of references is not allowed.

3.25 Write a program to declare reference variable to another variable. Display the assigned value using both the variables.

# include <iostream.h> 	 
# include <conio.h> 	 
# include <stdio.h> 	 
 
main( ) 	 
{ 	 
   clrscr( ); 	 
   int qty=10; 	 
   int & qt=qty; 	 

   printf ("qty Location qt Location"); 	 
   printf ("
=== ======== == ========"); 	 
   printf ("
%d %u %d %u",qt,&qt,qty,&qt);
   qt++;
   printf ("
%d %u %d %u",qt,&qt,qty,&qt); 	 
   qty--; 	 
   printf ("
%d %u %d %u",qt,&qt,qty,&qt); 	 
   return 0; 	 
}

OUTPUT:

qty      Location      qt      Location

===    ========    ==     ========

10         65524          10        65524

11         65524          11         65524

10         65524          10         65524

Explanation: In the above program, the variable qty is declared as integer variable and initialized with 10. The variable qt is declared as reference variable for variable qty. We can use variable qt to access the value of qty. Any change made in one of the variable changes the contents of both the variables. The contents of both variables and their address are always same. The variable qt and qty are modified using increment and decrement operator. But the contents and address printed on both variables are same. Figure 3.14 illustrates this.

Dereferencing Operator (*)

The asterisk (*) is a variable expression used to declare a pointer to a given type. In the example int *x; Where, x is a pointer of integer type, if the operand is a “pointer to function,” the result is a function designator. If the operand is a pointer to an object, the result is a lvalue, indicating that object. In the following conditions, the result of indirection is undefined.

(1) The expression is a null pointer.

(2) The expression is the address of an automatic variable and execution and it is out of scope.

images

Fig. 3.14 Reference variable

DIFFERENCE BETWEEN & AND * OPERATOR

The & is a reference operator. It displays address of the variable in the RAM. To display the address of the variable it should be preceded by the variable name.

Example:

int b=10;
printf ("%u",&b);

The above statement displays the address of the integer variable b.

The operator * is used to display the value stored at the address of the variable.

Example:

int b=10;
printf (" %d",*(&b));

The above statement displays the value of value stored at address of b i.e., value of b.

images

Fig.3.15 Difference between & and * operator

As shown in Figure 3.15, the statement (a) displays the contents of variable b. The statement b displays the address of the variable b and the statement (c) displays the value of variable b.

3.20 SCOPE ACCESS OPERATOR

Like C, 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 semicolons) allows a programmer to access a global (or file duration) name even if it is hidden by a local re-declaration of that name.

3.26 Write a program to use scope access operator. Display the various values of the same variable declared at different scope levels.

# include <iostream.h>
# include <conio.h>?

int a=10;
 
main( )
{
   clrscr( );
   int a=20;
   cout <<"::a=" <<::a;
   cout <<" a=" <<a;
   return 0;
}

OUTPUT:
::a=10 a=20

Explanation: In the above program, the integer variable a is declared before main( ) and initialized with 10. It is a global variable. In the function main( ) re-declaration of a is done and this time the variable a is initialized with 20. The first cout statement displays the global value of variable a i.e., 10. In this statement ::scope access operator is used to access the global value of the variable a. The second cout statement displays the local value of the variable a i.e., 20. Figure 3.16 explains use of scope access operator.

3.21 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( ). The syntax for new and delete are illustrated with suitable programs.

images

Fig. 3.16 Scope access operator

Following are the advantages of new operator over the function malloc( ).

(1) The new operator itself calculates the size of the object without the use of sizeof( ) operator.

(2) It returns the pointer type. The programmers need not take care of its typecasting.

(3) The new operator allocates memory and initializes the object at once.

(4) The new and delete operators are very easy in syntax. They can be overloaded.

The new operator

pointer memory variable = new data type[size];

Here, pointer memory variable is a pointer to the data type. The new operator allocates memory of specified type and returns back the starting address to the pointer memory variable. Here, the element size is optional and used when we want to allocate memory space for user defined data types such as arrays, classes and structures. If the new operator fails to allocate the memory it returns NULL, which can be used to detect failure or success of new operator.

(a) pv= new int;

(b) int *pv=new int (50);

(c) *p= new int [3]

In example (a) pv is a pointer variable of integer type. After allocation pv contains the starting address. In example (b), 50 is assigned to pointer variable pv. In example (c) memory for 3 integers i.e., 6 bytes are assigned to pointer variable p. Examples of new operator with arrays are given below:

(a)pv= new int [5] [2];                           // valid

(b) pv= new int [8][k][2]                        // invalid

(c) pv= new int [ ] [ 2 ] [ 2 ]         // invalid

The delete operator

The delete operator frees the memory allocated by the new operator. This operator is used when the memory allocated is no longer usable in the program. Follow the following syntax to use the delete operator:

Syntax:

(a) delete <pointer memory variable>

(b) delete [element size] <pointer memory variable>

Example:

(a) delete p;

(b) delete [5 ]p or delete [ ]p;

In example (a) the delete operator releases the memory allocated to pointer p. The example (b) is advantageous when we want to free the dynamically allocated memory of array. The new C++ compilers do not require element size.

3.27 Write a program to allocate memory using new operator.

# include <iostream.h> 		 
# include <conio.h> 		 
void main( ) 		 
{ 		 
   clrscr( ); 		 
   int *p= new int[3],k; 	// Memory allocation for 3 integers
 	 
for (k=0;k<3;k++) 		 
{ 		 
   cout <<"
Enter a Number : "; 	 
   cin >>*p; 	 

   p++; 	// Pointing to next location 	 
}
 			 
   p-=3; 	// Back to starting location
 	 
	cout <<"
 Entered numbers with their address are :
"; 	 
	for (k=0;k<3;k++) 	 
	{ 	 
	cout <<"
	"<<*p <<"	"<<(unsigned)p; 	// type casting 	 
	p++; 	 
	} 	 
   p - =3; 	 
   delete p; 	 
} 		 

OUTPUT
Enter a Number : 7

Enter a Number : 9

Enter a Number : 8

Entered numbers with their address are :

7    3658

9    3660

8    3662

Explanation: In the above program, p is an integer pointer variable. The new operator allocates memory required for three integers i.e., 6 bytes to pointer p. The first for loop reads integer through the keyboard and stores the number at memory location pointed by p as shown in Figure 3.17. Each time pointer p is incremented it shows next location of its type. The second for loop displays the number by applying the same logic. Before that, 3 again sets the pointer to the starting location by decrementing. The delete operator releases the memory allocated by the new operator.

images

Fig. 3.17 Memory map of integers

In the output of the program only starting memory location numbers are displayed. It is shown in Fig. 3.17.

sizeof( )

The sizeof( ) operator is used to return size occupied in bytes in memory by the variable. The sizeof( ) operator in C++ displays different values as compared to C. Program 3.28 illustrates this:?

3.28 Write a program to display number of bytes occupied by char data type.

# include <iostream.h>
# include <conio.h>
 
void main( )
{
   clrscr( );
   cout <<sizeof(‘a’);
}

OUTPUT

1

Explanation: In the above program, character constant uses sizeof( ) operator. The size determined is 1 byte. The same program C will display the size 2 bytes because C and C++ react differently with data types. In C, a character is considered as integer. Hence size displayed is 2 whereas in C++ it is considered as a character.

The size is the space occupied in memory in bytes by the variable. It depends upon data type of variable. Figure 3.18 describes the space occupied in the memory by the variable integer and float.

images

Fig.3.18 Size of int and float data

Example:

int x=5;
float f=3.14;

The integer variable occupies two bytes and float variable occupies four bytes in memory.

COMMENTS

In C++, a symbol // (double slash) is used as a comment symbol and there is no termination symbol. Comment begins with //symbol. A comment can be inserted anywhere in the line and whatever follows till the end of line is ignored. The C comments symbol, /* and */ are also valid in C++.

Examples:

// This is a C++ comment style. 	 
/* The C comment style is also valid in C++. */ 	 

3.22 COMMA OPERATOR

In C, every statement of the program is terminated by semi-colon (;). It is also applicable in C++ and in addition, 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.

Consider the following programs:

3.29 Write a program to use comma operator in place of semi-colon.

# include <iostream.h>
# include <conio.h>
 
void main( )
{
   clrscr( ),
   cout<<"
Use of comma operator",
   cout<<endl;
}

OUTPUT

Use of comma operator

Explanation: In function main( ), comma operator terminates the first two statements and the last statement is terminated by semi-colon.

All the above points are noticed in the Turbo C++ compiler. The reader is advised to follow his/her own observations.

3.30 Write a program to declare an integer, initialize it and display it. Terminate the statements using comma operator.

# include <iostream.h>
# include <conio.h>
void main( )
{
   int x;
   clrscr( ),
   x=10,
   cout<<"
 x = "<<x,
   cout<<endl;
}

OUTPUT

x = 10

Explanation: In the above program, the first and last statements are terminated by semi-colon. Comma operator terminates the statements in between these two statements.

3.23 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.

3.31 Write a program to use comma operator in if..else structure as scope indicator.

# include <iostream.h> 		 
# include <conio.h>
 		 
void main( ) 		 
{ 		 
  int x; 		 
  clrscr( ), 		 
  x=10; 		 
if (x==10) 	// if block 	 
  cout <<x<<endl, 	 
  cout<<x+1<<endl, 	 
  cout<<x+2<<endl, 	 
  cout <<"end of if block";// end of if block terminated by semi-colon 	 
  else 	 
  cout<<"False", 	// else block 	 
  cout<<"
End"; 	// end of else block terminated by semi-colon 	 
}

OUTPUT

10

11

12

end of if block

Explanation: In program 3.31, integer variable x is declared and initialized with 10. The if statement checks the value of x and executes respective blocks. The statements of if and else blocks are terminated by comma. The last statements of if block and else block are terminated by semi-colon to indicate the end of scopes. In this program the if block is executed.

3.32 Write a program to use comma operator in for loop to indicate the scope.

# include <iostream.h> 		 
# include <conio.h> 		 
 
void main( ) 		 
{ 		 
   int x; 		 
   clrscr( ), 		 
   x=5; 
 		 
   for (;x>0;x--) 		 
   cout<<"
x = "<<x,		// { 	 
   cout <<" In loop  ", 
   cout <<" In loop";		// }
 	 
   cout<<" Out of loop"; 	// executed after end of for loop 	 
} 

OUTPUT

x = 5 In loop In loop

x = 4 In loop In loop

x = 3 In loop In loop

x = 2 In loop In loop

x = 1 In loop In loop Out of loop

Explanation: In the above program, the statements terminated by comma are included in the scope of for loop. The first two statements are terminated by comma and the last statement terminated by semicolon i.e., end of scope of for loop.

SUMMARY

(1) C++ programs consist of objects, classes, functions, variables, and other statements.

(2) The C++ keywords are reserved words by the compiler. All C language keywords are valid in C++ and few additional keywords are added by ANSI committee.

(3) Identifiers are names of variables, functions, and arrays. They are user-defined names, consisting of sequence of letters and digits, with a letter as a first character.

(4) The constants in C++ are applicable to those values, which do not change during execution of a program. The two types of constants are literal and symbolic.

(5) C++ supports all data types of C.

(6) The keywords signed; unsigned, short, and long are type modifiers. A type modifier changes the meaning of the base data type to produce a new data type.

(7) The void type is added in ANSI C. It is also known as Empty data type.

(8) The enum is a keyword. It is used for declaring enumeration data types. C++ allows us to declare variable of enum data type and enum without tag name.

(9) Variables are used to store constants i.e., information. A variable is a sequence of memory locations, which are used to store the assigned constant.

(10) C++ permits declaration of variables anywhere in the program.

(11) The initialization of variable at run-time is called as dynamic initialization.

(12) C++ supports all the operators of C. The list of newly introduced operator is described in Table 3.4.

(13) The referencing operator is used to define referencing variable. A reference variable prepares an alternative (alias) name for previously defined variable.

(14) The asterisk (*) in a variable expression is used to declare a pointer to a given type.

(15) The scope access (or resolution) operator :: (two semicolons) allows a programmer to access a global (or file duration) name even if it is hidden by a local re-declaration of that name.

(16) The new operator creates an object and delete destroys the object. These operators are easy in writing as compared to malloc( ) and calloc( ).

(17) C++ reference types, declared with & operator, are nearly identical but not exactly same to pointer types. They declare aliases for objects variables and allow the programmer to pass arguments by reference to functions.

(18) In C++ a symbol // (double slash) is used as a comment symbol and there is no termination symbol.

(19) C++ supports all the decision making and loop control statements of C.

EXERCISES

[A] Answer the following questions.

(1) Describe different parts of C++ programs.

(2) List the new keywords in C++ with their functions.

(3) What are identifiers, variables, and constants?

(4) Which are the two types of constants? Describe them with suitable examples.

(5) Describe the statements for creating constants. Explain with examples.

(6) What is the use of the keyword void? In how many ways can it be used with function?

(7) What is the difference between variable declaration in C and C++?

(8) What is dynamic initialization? Is it possible in C?

(9) Describe the use of scope access operator (::) and reference operator (&).

(10) What are the advantages of new operator over malloc ( ) function?

(11) What are type modifiers? Why are they essential in C++?

(12) Describe types of derived data type.

(13) Describe the following terms

(a) Precedence of operators in C++

(b) Type modifiers

(c) Constant pointers

(14) Explain typecasting. What are explicit and implicit type conversions?

(15) Explain wrapping around of value.

(16) Explain use of comma operator.

[B] Answer the following by selecting the appropriate option.

(1) In C++, the symbol used for writing comments is

(a) //

(b) //* *//

(c) */ */

(d) none of the above

(2) The :: is known as

(a) scope access operator

(b) double colons

(c) both (a) and (b)

(d) none of the above

(3) The delete operator is used

(a) to delete object

(b) to delete file

(c) both (a) and (b)

(d) none of the above

(4) The new and delete are

(a) operators

(b) keywords

(c) both (a) and (b)

(d) none of the above

(5) The new operator

(a) allocates memory

(b) releases memory

(c) both (a) and (b)

(d) none of the above

(6) What will be the output of the following program?

     # include <iostream.h>
 	 
     void main( ) 	 
   { 	 
     char *n; 	 
     cout <<sizeof(n); 	 
   } 	 

(a) 2

(b) 1

(c) 4

(d) none of the above

(7) What will be the value of c after execution of the following program?

    # include <iostream.h>
    void main( ) 	 
   { 	 
    int *p, c=0; 	 
    p=new int[4]; 	 
    for (int x=0;x<2;x++) 	 
    c=c+sizeof((p+x)); 	 
   } 		 

(a) c=4

(b) c=8

(c) c=2

(d) c=0

(8) The union declared without tag name is called as

(a) anonymous union

(b) nameless union

(c) unknown union

(d) void union

(9) What will be the output of the following program?

    # include <iostream.h>
    void main( )
  {
  {
    for ( int i=0;i<5;i++)
    { cout <<i; } 
    cout <<" i ="<<i;
  }

(a) 01234 i =5

(b) undefined symbol i

(c) 012345

(d) none of the above

[C] Attempt the following programs.

(1) Write a program to allocate memory using new operator for 10 integers. Read and display the integers.

(2) Write a program to evaluate following series:

(a) x=x2+x3+ --xn

(b) y=2x+2*(x3-10)

(c) z=x-y (Use (a) and (b))

(d) Display square root of z.

(3) Write a program to display A to Z characters using while loop.

(4) Write a program to draw a square box. Use for loop.

(5) Write a program to declare and initialize a variable. Create a reference variable. Display the value of actual variable using reference variable.

(6) Given the Vander Wall's constants x and y for a gas. Calculate the critical temperature, pressure, and volume using the following formulas:

ct= 8x/27Rb

p=x/27b2

v=3b

R= 0.0821 dm3atm/mol/k

Read values of x and y and calculate and print the values of ct,p, and v.

(7) The sum of the square of the first n natural numbers is calculated by the formula sum=n (n+1) * (2n+1)/ 5. Read value of n through the keyboard and calculate the sum of square of first n natural numbers.

(8) Write a program to calculate

(a) Area of circle ( area=3.12*r2)

(b) Circumference of the circle (c=2*3.12*r)

(c) Volume of the cylinder (v=3.12*r2*h)

(d) Surface area of the closed cylinder (s=2*3.12*r*h+2*3.12*r2)

(e) Volume of sphere ( v=4/3*3.12*r3)

(9) A company gives following rates of commission for the monthly sales of the product:

Below Rs. 15000/- No commission
15001-20000/- 5%
20001-30000/- 10%
Above 30000/- 12%

Write a program to read the sales and display the commission.

(10) Write a program to display the sum of odd numbers between 1 to 150.

(11) A worker takes a job for 31 days. His pay for the first day is Rs. 20. His pay for the second day is Rs. 40. Each day's pay is twice what he gets in the previous day. What will be the total pay for 31 days?

(12) Write a program to find the range of the given numeric data.

(Range smallest number-largest number)

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.225.255.178