Chapter2 PDF

Download as pdf or txt
Download as pdf or txt
You are on page 1of 6

Chapter 2

C++ Language Basic Syntax


Standard Conversion and Promotions:
When there are two operands of different types in an expression, the lower-type
variable is converted to the type of the higher-type variable. For example, if one operand
is of type int and other is of float, both are converted into float type. Thus, if data types
are mixed in an expression, C++ performs the conversions automatically. This process is
called implicit or automatic conversion. An example:

void main()
{ int a=10;
float b=40.5, result;
result=a+b;
cout<<"The sum is "<<result; }
Output:
The sum is 50.5.
In this case, variable a is of type int while b is of type float. While solving the
expression a+b, the temporary variable of type float is created to store value of a and then
two float values are added. The result is of type float and stored in variable result. Here,
data type int is promoted to float. Thus, it is also known as standard data type
promotion.
The other implicit conversions are
Int and float -> float
Int and long -> long
Int and double -> double
Long and float -> float
Float and double -> double

But, sometime programmer needs to convert a value from one type to another explicitly
in a situation where the compiler will not do it automatically. This type of conversion is
called explicit conversion or type casting. An example:
void main()
{ int a=4000;
long result;
result=a*100;
cout<<"The product is "<<result; }
Output:
The product is 6784 // Error!!!!!

The corrected version is:


void main()
{ int a=4000;
long result;
result=long(a)*100; //type casting
cout<<"The product is "<<result; }
Prepared By: 1
Er. Dipesh Bista
Acme Engineering College
Output:
The result is 400000 // correct

Here, while solving the expression long(a)*100 in above program, integer type
variable a is converted into long type. For this, a temporary variable of type long is
created to store value of a and this long value is multiplied by 100 and result is also of
type long. The long result is stored in variable result.
Without casting, the result is not correct. This is because multiplication of two
integers (i.e. a and 100) results integer value (i.e. 4000000). But this integer value is
beyond the range of integer. Thus, garbage value is stored in result variable.

Array and Pointer in C++:


Array:
Array is a data structure that store a number of data items as a single entity
(object). The individual data items are called elements and all of them have same data
types. Array is used when multiple data items that have common characteristics are
required (in such situation use of more variables is not efficient). In array system, an
array represents multiple data items but they share same name. The application of array is
similar to that in C. The only difference is while initializing character arrays. When
initializing a character array in C, the compiler will allow us declare the array size as the
exact length of the string constant. For example:
char name[5]=”shyam”;
is valid in C and null character \0 is added at the last of array automatically. But in C++,
the size should be one larger than the number of characters in the string. i.e.
char name[6]=”shyam”;

Pointer:
A pointer is a variable that stores a memory address of a variable. Pointer can
have any name that is legal for other variable and it is declared in the same fashion like
other variables but is always preceded by ‘ *’ ( asterisk) operator. Pointers are declared
and initialized as in C. The additional feature of C++ is that has concept of constant
pointer and pointer to constant. The constant pointer is defined as
Data_type * const ptr_name;
An example:
void main()
{ int j=10;
int *const ptr=&j; //constant pointer
*ptr=20;//OK
ptr++; //Error
}
Pointer to Constant:
It is defined as
Data_type const *ptr_name;
An example:
void main()
{
Prepared By: 2
Er. Dipesh Bista
Acme Engineering College
int const j=10;
int const * ptr=&j;// pointer to constant
*ptr=20;//Error
ptr++; //OK
}

new and delete Operators:


As we know that the process of allocating and freeing memory at run time is
called Dynamic Memory Allocation. This conserves the memory required by the program
and returns this valuable resource to the system once the use of reserved space is utilized.
In C, the functions like calloc(), malloc(), free(), realloc() are used for memory
management at run time. C++ supports two new unary operators new and delete for
memory management at run time along with these C’s functions. An object can be
created by using new and destroyed by using delete.
Syntax for new:
pointer_variable=new data_type;
Where pointer_variable is predefined pointer of type data_type and data_type is
user-defined or built in data type of C++. The new operator allocates sufficient memory
to hold a data object of type data_type and returns the address of the object. The pointer
variable holds the starting address of allocated memory.
Examples:
int *ptr;
ptr=new int;
The above statement allocates two bytes of memory and is stored by pointer variable
ptr.

Characteristics:
¾ Memory can be initialized using new operator. This is done as
Pointer _variable= new data_type(initial_value);
e.g. int *p;
p=new int(35);
will allocates two bytes of memory and 35 is allocated at this memory initially.
¾ new can be used to allocate a memory space for data types including user defined
types such as arrays, structures and classes. Its syntax is
pointer_variable=new data_type[size]; // for array
e.g.
int *p;
p=new int[100];
will allocates 200 bytes memory and starting address is stored at pointer
variable p.

Advantages of new operator over the function malloc()


¾ It automatically computes the size of the data object while we need to use sizeof
operator in the case of malloc() function.
¾ It is possible to initialize the object while creating the memory space.
Prepared By: 3
Er. Dipesh Bista
Acme Engineering College
¾ It automatically returns the correct pointer type, so that there is no need to use a
type caste. In syntax of malloc() function
ptr_variable=(data_type*) malloc(size_of_block);
data_type within () is for type casting which is not needed in the case of new operator.

delete:
If a program reserves many chunks of memory using new, eventually all the available
memory will be reserved and the system will crash. To ensure safe and efficient use of
memory, the new operator is matched by a corresponding delete operator. This operator
returns the memory to the operating system when a data object in no longer needed.
Thus, delete operator is used to release the memory space for reuse by destroying the
object when it is no longer needed. The syntax
delete pointer-variable; // general syntax
delete [] pointer-variable; // in case of array

An example, a program which asks for a number of students at run time and
according to the number of students in a class, the program reserves the memory to store
percentage of each student and finally calculates average percentage of class.
#include<iostream.h>
void main()
{
int num,*ptr;
float sum=0;
cout<<"How many number of students?"<<endl;
cin>>num;
ptr=new int[num];
cout<<"Enter each students marks"<<endl;
for(int i=0;i<num;i++)
{
cin>>*(ptr+i);
sum+=*(ptr+i);
}
float avg= sum/num;
cout<<"The average is "<<avg;
delete []ptr;
}

const:
This is C++ qualifier used for creating symbolic constant. Its syntax is
const data_type variable_name= value;
e.g. const int size=10;
It specifies that the value of a variable (here, size) will not change throughout the
program. Any attempt to alter the value of a variable defined with this qualifier will give
error message by compiler. It is used for variables which do not change throughout the

Prepared By: 4
Er. Dipesh Bista
Acme Engineering College
program like PI while calculating area of circle. In C++, the variable defined with this
qualifier const should be initialized.

Enumeration:
The dictionary meaning of enumeration is counting, go through a list of articles naming
them one by one. The process enumeration provides user defined data type, called
enumerated data type which provides a way for attaching names to numbers. The syntax
is
enum tag_name {name1, name2, name3, ….};
e.g. enum flag{false, true};
enum colour{red, blue, green, white};
Here, colour is enumerated data type whose permissible values are red, blue, green and
white. Here, possible values red, blue, green and white are also called enumerators. These
enumerators are attached with numbers 0,1,2 and 3 (i.e. o for red, 1 for blue and so on).
Variables can be defined using this enumerated data type. These variables store only
those values defined while defining enumerated data type.
e.g.
colour foreground;
foreground=red // ok
foreground=yellow; // not ok as yellow is not possible value for data type colour

By default, the enumerators are assigned integers values starting with o for the first
enumerator, 1 for second and so on. These can be explicitly assigned by the programmer
as following.
enum colour{red=7,blue, green, white}; // here, blue=8, green=9 and white=10

Characteristics:
¾ Although the enumerated data types are treated internally as integers, C++ does
not permit an int value to be automatically converted to an enum value. E.g.
colour foreground=2; // error
colour foreground= (colour)2 // ok
¾ An enumerated value i.e. enumerator can be used in place of an int value. E.g.
int num= red; // ok
¾ The enumeration provides an alternative means for creating symbolic constants.
The enumerator’s value can be changed in the program.
¾ The anonymous enums (without enum_tag_name) can be created in C++.
e.g. enum {red,blue,green,white};

An example:
#include<iostream.h>
void main()
{
enum days{sun,mon,tue,wed,thu,fri,sat};
days day1,day2;
int mid_day;
day1=sun;
Prepared By: 5
Er. Dipesh Bista
Acme Engineering College
day2=sat;
mid_day=wed;
cout<<"day1= <<day1<<endl<<"day2="<<day2<<endl<<"Middle="<<mid_day;
}

Output:
day1=0
day2=6
Middle=3

An another example which asks a number and test it for even or odd.
#include<iostream.h>
#include<conio.h>
void main()
{
clrscr();
int num;
enum flag{false, true};
flag even;
cout<<"Enter a number to check even or odd"<<endl;
cin>>num;
if(num%2==0)
even=true;
else
even =false;
if(even)
cout<<"The number is even";
else
cout <<"The number is odd";
getch();
}

Comments:
Comments in programming languages are those statements which are not needed to
compile by the compiler. C++ supports both single line and multiple line comments.
Single line comment is also known as double slash comment (i.e. //). It this comment is to
be used for multiple line, we should use // for each line separately.
e.g.
//This is single line
// comment used for multiple line
Again, it supports C style comment (i.e. /* */). This type of comment is generally used
for multiple lines. The lines between /* and */ are not compiled.

Prepared By: 6
Er. Dipesh Bista
Acme Engineering College

You might also like