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

Module2 C++

This document is an introduction to functions in C++ programming, covering essential concepts such as tokens, keywords, identifiers, constants, operators, and function prototyping. It explains the differences between C and C++ in terms of naming conventions, the use of the scope resolution operator, and various types of expressions. Additionally, it discusses advanced topics like call by reference, return by reference, and inline functions to enhance programming efficiency.

Uploaded by

pallavi
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 views15 pages

Module2 C++

This document is an introduction to functions in C++ programming, covering essential concepts such as tokens, keywords, identifiers, constants, operators, and function prototyping. It explains the differences between C and C++ in terms of naming conventions, the use of the scope resolution operator, and various types of expressions. Additionally, it discusses advanced topics like call by reference, return by reference, and inline functions to enhance programming efficiency.

Uploaded by

pallavi
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/ 15

Introduction to C++ Programming BPLCK205D

Module-2
Functions in C++: Tokens – Keywords – Identifiers and constants – Operators in C++ – Scope resolution
operator – Expressions and their types – Special assignment expressions – Function prototyping – Call by
reference – Return by reference – Inline functions -Default arguments – Function overloading.

FUNCTIONS IN C++
2.1 Tokens
The smallest individual units in a program are known as Tokens, most of the C++ tokens similar to
the C tokens with exception of some addition and minor modification. Types of C++ tokens are as follows:
 Keywords
 Identifiers
 Constants
 Strings
 Operators

Fig 2.1: Types of C++ Tokens


2.2 Keywords
Table 2.1: C++ Keywords

Pallavi C S Assistant Prof. Dept. of Data Science AIT, Chikkamagaluru Page 1


Introduction to C++ Programming BPLCK205D
The keywords implement specific C++ language feature. They are explicitly reserved identifier and
cannot be used as name for program variable or other user defined program elements.
In Table 2.1 Boldface indicates the C keywords, C keyword are 32, totally C++ keywords are 48 with
ANSI C++ added 15 keywords totally 63 keywords in C++.
Many of the keyword common for both C and C++, the additional keyword have been added to the
ANSI C++ keyword in order to enhance the its feature and make it the object oriented language ANSI C+
+ standard committee has added some more keywords to make the language more versatile.

2.3 Identifiers and constants


 Identifiers: Identifiers refer to the name of variables, functions, arrays, classes, etc. created by
the programmer; they are the fundamental requirement of any language.
Each language has its own rules for naming this identifier the rules are both C and C++,
Rules for naming identifiers:
 Only alphabetic characters, digits, and underscores are permitted.
 Identifier names cannot start with a digit or any special character.
 The upper case and lower case letters are distinct
 A declared keyword cannot be used as a variable name.
A major difference between C and C++ is the limit on the length of name, while ANSI C recognizes only
the first 32 character in a name, ANSI C++ places no limit on its length and therefore all the character in a
name are significant
While naming a variable which is being shared by more than one file containing C and C++
programs. Some operating systems impose a restriction on the length of such variable name.

 Constants: constant refer to fixed values that do not change during the execution of a program
Like C, C++ supports several kinds of literal constant, they include integers, characters, floating point
numbers and strings, literal constant do not have memory location.
Example:
123 //decimal integers
12.34 //floating point integer
037 //octal integer
0X2 //hexadecimal integer
“C++” //string constant
‘A’ //character constant
L‘ab’ //wide character constant
The wchar_t type is a wide character literal introduced by ANSI C++ and intended for character sets
that cannot fit in a single byte. Wide character literal begin with letter L

Pallavi C S Assistant Prof. Dept. of Data Science AIT, Chikkamagaluru Page 2


Introduction to C++ Programming BPLCK205D
2.4 Operators in C++
C++ has a rich set of operator. All C operator are valid in C++ also in addition C++ introduced some new
operator
<< Insertion operator
>> Extraction operator
Some other new operators are
:: scope resolution operator
: :* pointer – to – member declarator
–>* pointer – to – member operator
.* pointer – to – member operator
Delete memory release operator
endl line feed operator
new memory allocation operator
setw field with operator
C++ also allow us to provide new definitions to some built in operators, we can give several meaning to
an operator depending upon the type of arguments used this process in known as operator
overloading.

2.5 Scope resolution operator


Like C, C++ is also a blocks-structured language, Blocks and scopes can be used in constructing programs.
We know that the same variable name can be used to have different meaning in different blocks. The scope
of the variable extends from the point of its declaration till the end of the block containing the declaration. A
variable declared inside a block is said to be local to that block.
…………
…………
{
int x = 10;
…………
…………
}
…………
…………
{
int x = 1;
…………
…………
}
The two different declaration of x refer to different memory location containing different value.
Statement in the second block cannot refer to variable x declare in first block, and vice versa.

Pallavi C S Assistant Prof. Dept. of Data Science AIT, Chikkamagaluru Page 3


Introduction to C++ Programming BPLCK205D
…………
…………
{
int x = 10;
…………
…………
{
int x = 1; Block 1
………… Block 2
…………
}
…………
}
Block 2 contained Block 1. Note that a declaration in an inner block hides a declaration of the same variable
in an outer block and therefore each declaration of x causes it to refer to a different data object. Within the
inner block, the variable x will refer to the data object declared therein.
In C, the global version of a variable cannot be accessed from within the inner block. C++ resolves this
problem by introducing a new operator : : called the scope resolution operator. Its takes the fallowing
forms.
: : variable_name

Example Program of scope operator:


#include <iostream>
Using namespace std;
int m=10; //global m
int main ( )
{
int m = 20; // m declared, local to main
{
int k=m;
int m = 30; // m declared again
// local to inner block
cout << “ we are inner block \n ”;
cout << “k = ” << k <<” \n”;
cout << “ m = ”<<m<<” \n”;
cou<< “: :m = ”<< : :m << “ \n”
}
cout << “\n we are in outer block \n”;
cout << “m = ” << m<<”\n”;
cout << “: :m << m <<”\n”;
return 0:
}

Pallavi C S Assistant Prof. Dept. of Data Science AIT, Chikkamagaluru Page 4


Introduction to C++ Programming BPLCK205D
Output:
we are in inner block
k=20
m=20
: : m=10
we are in outer block
m=20
: : m=10
Note: : : m is always refer to a global value

2.6 Expressions and their types


An expression is a combination of operators, constant and variable arranged as per the rules of language.
An expression may consist of a one or more operands and zero or more operators to produce a value
expression may be a fallowing seven types
 Constant expressions
 Integral expressions
 Float expressions
 Pointer expressions
 Relational expressions
 Logical expressions
 Bitwise expressions
An Expression may also use combination of above expressions such expressions are known as compound
expressions
 Constant expressions
Constant Expressions consists of only constant values. A constant value is one that doesn’t change.
Example:
15
20+5/2.0
‘x’
 Integral expressions
Integral Expressions are those which produce integer results after implementing all the automatic and
explicit type conversions.
Example:
m m*’x’
m*n-5 5+int(2.0) where m and n are integer value

Pallavi C S Assistant Prof. Dept. of Data Science AIT, Chikkamagaluru Page 5


Introduction to C++ Programming BPLCK205D
 Float expressions
Float Expression are those which after all conversion produce floating point result.
Example:
x+y
x*y/10
5+float (10)
10.75
Where x and y are floating point variables
 Pointer expressions
Pointer Expressions produce address values
Example:
&m
ptr
ptr+1
“xyz”
Where m is a variable ptr is a pointer
 Relational expressions
Relational Expressions yield results of type bool which takes a value true or false.
When arithmetic expressions are used on either side of a relational operator, they will be evaluated first
and then the results compared. Relational expressions are also known as Boolean expressions.
Example:
x<=y
a+b==c+d
m + n > 100
 Logical expressions
Logical Expressions combine two or more relational expressions and produces bool type results.
Example:
a>b && x+==10
x==10 || y=5
 Bitwise expressions
Bitwise Expressions are used to manipulate data at bit level. They are basically used for testing or shifting
bits. Shift operators are often used for multiplication and division by powers of two.
Example:
x<<3 // shift three bit position to left
y<<1 //shift one bit position to right

Pallavi C S Assistant Prof. Dept. of Data Science AIT, Chikkamagaluru Page 6


Introduction to C++ Programming BPLCK205D
2.7 Special assignment expressions
 Chained Assignment
 Embedded Assignment
 Compound Assignment
 Chained Assignment
x = (y = 10);
Or
x = y = 10;
First 10 is assigned to y and then to x;
A chained statement cannot be used to initialize at the time of declaration.
float a = b = 12.34; //wrong
Is illegal this may write as fallow
float a = 12.34, b = 12.34; //correct
 Embedded Assignment
x = (y = 50) +10;
(y = 50) is an assignment expressions known as embedded assignment here value is assigned to y and then
the result 50 + 10 = 10 is assigned to x. the statement is identical to
x = 50;
x = y + 10;
 Compound Assignment
Like C, C++ support Compound Assignment operator which is a combination of the assignment operator
with a binary arithmetic operator.
x = x + 10;
May be written as
x + = 10;
The operator + = is known as compound assignment operator or short hand assignment operator.
The general from of compound assignment operator is
variable op = variable2
Where op is a binary arithmetic operator this means that
variable1 = variable1 op variable2

2.8 Function prototyping


Function prototype is one of the major improvements added to C++ functions. The prototype describes the
function interface to the compiler by giving details such as the number and type of arguments and their type
of return value.

Pallavi C S Assistant Prof. Dept. of Data Science AIT, Chikkamagaluru Page 7


Introduction to C++ Programming BPLCK205D
With functions prototyping a template is always used the template to ensure proper arrangement are passed
and the return value treated correctly
With function prototyping a template is a always used when declaring and defining a function. C also
used prototyping but it was introduced first in C++ by Bjarne Stroustrup and the success of this feature
inspire the ANSI C committee adopted it.
Function prototyping is a declaration statement in the calling program and is of the fallowing form
type function_name(arguments_list);
The arguments list contains the type and name of the arguments that must be passed to the function
Example:
float volume (int x, float y, float z); //legal
We cannot combine the above declaration like
Float volume (int x, float y, z) // illegal
Dummy variable declaration
float volume (int, float, float)
Is acceptable at the place of declaration at this stage that compiler only checks for the type of arguments
when function is called.
The variable name in the prototype just act as a place holder and therefore if names are used they
don’t have match the names used in the function call or function definition
Example:
float volume (int a, float b, float c)
{
float v = a*b*c;
-- -- --- --- -- - --
- -- -- -- -- -- -- -
}
The function volume ( ) can be invoked in a program
float cube1 = volume ( b1, w1, h1); //function call
The variable b1, w1, h1 are known as the actual parameters which specifying the dimensions of cube1
we can also declared empty arguments for a function
void display( );
In C++ is identical to the
void display (void);
C++ function can also have open parameters list by use of ellipse in the prototype as shown below:
void do_something( _ _ _ );

Pallavi C S Assistant Prof. Dept. of Data Science AIT, Chikkamagaluru Page 8


Introduction to C++ Programming BPLCK205D
2.9 Call by reference
In traditional C, a function call pass arguments by value the called function creates a new set of variables and
copies the values of arguments into them.
The function does not have access to the actual variable in the calling program and can only work on
the copies of the values. This mechanism fine if the function does not need to alter the values of the original
variables in the calling program. But they may arise situation where would like to change the values of
variable in the calling program.
Provision of the reference variable in C++ permits us to pass parameter to the function by reference
when we pass arguments by reference the “formal” arguments in the called function become aliases to the
actual arguments in the calling function.
void swap (int &a, int &b)
{
int t = a;
a = b;
b = t;
}
If m and n are the two integer variable the function call is
Swap (m, n)
Will exchange the values of m and n using their aliases (reference variable) a and b
void swap (int *a, int *b)
{
int t;
t = *a; //* assign the value at address a to t*/
*a = *b; //* put the value at b into a*/
*b = t; c //* put the value at t into b*/
}
This function can be called as fallows
swap1 (&x, &y); //*call by passing address of variable*/
2.10 Return by reference
A function can also return a reference
int &max(int &x, int &y)
{
if (x>y)
return x:
else return y:
}

Pallavi C S Assistant Prof. Dept. of Data Science AIT, Chikkamagaluru Page 9


Introduction to C++ Programming BPLCK205D
Since return type of max ( ) int & the function returns reference to x and y not a values then a function call such as
max (a, b) will yield a reference to either a or b depending on their values
max ( a, b) = -1;
Is legal and assigns -1 to an if its larger otherwise -1 to b

2.11 Inline functions


One of the objectives of using functions in a program is to save some memory space, which become
appreciable when a function is likely to be called many times. However every time a function is called it
takes a lot of extra time in executing a series of instructions for task. Such as jumping to the function saving
register, pushing the arguments into the stack and returning to the calling function.
When a function is small a substantial percentage of execution time may be spent in such overheads
one solution to this problem is to use macro definitions popularity known as macros.
Pre-processor macros are popular in C, the major drawback with macros is that they or not really
functions and therefore the inline function are defined follows
inline function_header
{
Function body
}
Example
inline double cube ( double a)
{
return (a*a*a)
}
The above inline function can be invoked as fallows;
c = cube ( 3.0 )
d = cube ( 2.5+ 1.5 )
The result of the above become;
c = 27
d = 64
Usually the function are made inline when they are small enough to be defined in one or more line
Example
inline double cube ( double a ) { return ( a*a*a);}
Some of the situations where inline expansion may not work that are
 For function returning values if a loop, a switch or a goto exist
 For function not returning values if a return statement exists
 If function contain static variable
 If inline function are recursive

Pallavi C S Assistant Prof. Dept. of Data Science AIT, Chikkamagaluru Page 10


Introduction to C++ Programming BPLCK205D
Example program (illustrate the use of inline function)
#include <iostream>
using namespace std;
inline float mul (float x, float y);
{
return ( x*y );
}
inline double div (double p, double q)
{
return ( p/q );
}
int main ( )
{
float a = 12.345;
float b = 9.82;
cout << mul (a, b) << “\n”;
cout << div (a, b) << “\n”;
return 0;
}
Output
121.228
1.25713
2.12 Default arguments
C++ also us to call a function without specifying all its arguments, in such case the function assigns a default
value to the parameter which does not have matching the arguments in the function call.
Default values are specified when the function is declared the compiler looks at the prototype to see how
many arguments a function uses and alters the program for possible default values.
float amount ( float principal, int period, float rate = 0.15)
The default value of 0.15 the argument rate a subsequent function call like fallows
value = amount (5000, 7); // one argument is missing 5000 to principal, 7 to period
volume = amount (5000, 7, 0.15); // no missing arguments
A default arguments is checked for type at the time of declaration and evaluated at time of call
int mul (int i, int j = 5, int k =10); //legal
int mul (int i = 5, int j); //illegal
int mul (int i = 0, int j, int k = 0); //illegal
int mul (int i = 2, int j = 5, int k = 0); //illegal

Pallavi C S Assistant Prof. Dept. of Data Science AIT, Chikkamagaluru Page 11


Introduction to C++ Programming BPLCK205D
Advantages:
 We can use default arguments to add new parameters to the existing function
 Default arguments can be used combine similar function into one
Default arguments example program
#include <iostream>
using namespace std;
int main ( )
{
float amount;
float value (float p, int n, float r = 0.15);
void printline (char ch = ‘*’, int len = 40);
printline ( );
amount = value (5000, 00, 5);
cout << “\n final value = “ << amount <<”\n\n”;
printline ( ‘=’);
retuen 0;
}
float value (float p, int n, float r);
int year =1;
float sum = p;
while (year <=n)
{
sum = sum*(1+r);
year = year + 1;
}
Return (sum);
}
void printline ( char ch, int len)
{
for (int i = 1; i<=len; i++)
printf (“%c”, ch)
printf (“\n”)
}
Output
Final value = 10056.8

Pallavi C S Assistant Prof. Dept. of Data Science AIT, Chikkamagaluru Page 12


Introduction to C++ Programming BPLCK205D
2.13 Function overloading
Over loading refer to the use of the same thing for the different purpose. C++ also permits overloading of
function this means that we can use the same function name to create function that perform a verity of
different tasks this known as function polymorphism in oop.
Using the concept of function overloading we can design a family of function which one function
name but with different argument list.
For example on overload add ( ) function handles different types of data as shown below
// declarations
int add ( int a, int b); //prototype 1
int add ( int a, int b, int c); //prototype 2
int add ( int a, int b, int c, int d); //prototype 3
double add ( double x, double y); //prototype 4
double add ( int p, double q); //prototype 5
double add (double p, int q); //prototype 6

// function call
cout << add ( 5, 10); //uses prototype 1
cout << add ( 5, 10.0); //use prototype 5
cout << add ( 12.5, 7.5); //use prototype 4
cout << add ( 5, 10, 15); //use prototype 2
cout << add ( 5, 10, 15, 20); //use prototype 3
cout << add ( 0.75, 5); //use prototype 5
the function call first matches the prototype having the same number and type of arguments and then call the
appropriate function for execution a best matches must be unique the function selection involves the
following steps
1. The complier tries to find and exact match in which the types of actual arguments are the same and
use that function
2. If an exact match is not found the compiler uses the integral promotions to the actual arguments such
as
char to int
float to double
3. When either ( above 2) of them fails the complier tries to use the built in conversion to the actual
arguments and then uses the function whose match in unique
long square ( long n)
double square ( double x)

Pallavi C S Assistant Prof. Dept. of Data Science AIT, Chikkamagaluru Page 13


Introduction to C++ Programming BPLCK205D
A function call such as
square (10)
4. If all the step fail ( above 3) then the compiler will try the uses user defined conversion in
combination with integral promotions and built in conversions to find unique match
Example program

#include <iostream>
using namespace std;
int volume ( int );
double volume ( double, int );
long volume ( long, int, int);
{
cout << volume (10) << “\n”;
cout << volume ( 2.5, 8) << “\n”;
cout << volume ( 100L, 75,15) << “\n”;
return 0;
}
int volume ( int s)
{
return ( s*s*s);
}
double volume (double r, int h)
{
return ( 3.14519*r*r*h);
}
long volume (long l, int b, int h )
{
return ( l*b*h);
}
Output
1000
157.26
112500

Pallavi C S Assistant Prof. Dept. of Data Science AIT, Chikkamagaluru Page 14


Introduction to C++ Programming BPLCK205D
ASSIGNMENT QUESTIONS FOR INTRODUCTION TO C++ PROGRAMMING
MODULE‐2
Q1. Describe the tokens explain its types with suitable example (Page 27, 28)

Q2. Discuss operators and its types with suitable examples. (Page 29, 30, 31)

Q3. With example program explain the scope regulation operator (Page 30, 31)

Q4. Discuss expressions and their types with suitable examples. (Page 31, 32)

Q4. What are the Special assignment expressions and explain each with suitable example. (Page 33)

Q5. Explain the function prototyping with suitable example program. (Page 33, 34)

Q6. What are reference variables in C++ (call by reference and return by reference) Discuss with examples.
(Page 35, 36)

Q7. Illustrate Inline function and its syntax. Write a C++ program to implement Inline function. (Page 36,
37)

Q8. Explain default arguments with example program (Page 37, 38)

Q9. What are steps to fallow to process in function overloading explain in detail with example program.
(Page 39, 40)

Pallavi C S Assistant Prof. Dept. of Data Science AIT, Chikkamagaluru Page 15

You might also like