Introduction to c++ programming Module 2 notes
MODULE -2
Functions in C++:
Tokens – Keywords –
Identifiers and
constants – Operators Tokens
in C++ – Scope the smallest individual units in a program are
resolution operator – known as tokens.
Expressions and their C++ has the following tokens: Keywords
types – Special Identifiers Constants Strings Operators.
assignment
expressions –
Function prototyping Keywords
– Call by reference –
Keywords are explicitly reserved identifiers and
Return by reference –
cannot be used as names for the program variables
Inline functions -
or other user-defined program elements.
Default arguments –
Function overloading. For example, a variable or function cannot be
named as ‘int’ because it is reserved for declaring
integer data type.
There are 95 keywords reserved in C++.
Eg: [Link],int,private,public,void..etc.
Identifiers and Constants:
Identifiers refer to the names of variables, functions, arrays, classes, etc.
created by the programmer.
The following are the rues to be followed while declaring identifiers
1. Only alphabetic characters, digits and underscores are permitted.
2. The name cannot start with a digit.
3. Uppercase and lowercase letters are distinct.
4. keyword cannot be used as a variable name.
Dept of CSE Vanitha G P
Introduction to c++ programming Module 2 notes
Constants: constants are used to define variables at the time of initialization
and the assigned value cannot be changed after that(value remains constant).
Syntax: const type name = val
Ex:const int pi=3.142 // value of pi remains constant.
Strings
In C++, a string is not a built-in data type like ‘int’, ‘char’, or ‘float’. It is a class
contains sequence of charcters.
Syntax: string variable_name;
Ex: string name=”Rohith”;
Operators
C++ has a rich set of operators. All C operators are supported in C++ also.
:: Scope resolution operator
::* Pointer-to-member declarator
>* Pointer-to-member operator
.* Pointer-to-member operator
delete Memory release operator
end1 Line feed operator
new Memory allocation operator
setw Field width operator
>> extraction operator
<< insertion operator
Eg:
#include<iostream>
Using namespace std;
Dept of CSE Vanitha G P
Introduction to c++ programming Module 2 notes
Int main()
{
Int a;
cin>>a;// extraction operator
cout<<”value of a is”<<a<<endl;//insertion operator,endl
return 0;
}
Scope Resolution Operator ::
If the global variable name is same as local variable name, the scope resolution
operator will be used to call the global variable.
Eg:
#include <iostream>
using namespace std;
// Global x
int x = 3;
int main()
{
// Local x
int x = 10;
// display the global
x cout << ::x;
return 0;
}
Dept of CSE Vanitha G P
Introduction to c++ programming Module 2 notes
Expressions and Their Types
An expression may consist of one or more operands, and zero or more
operators to produce a value.
Expressions may be of the following seven types:
Constant expressions
Integral expressions
Float expressions
Pointer expressions
Relational expressions
Logical expressions
Bitwise expressions
Type Definition example
Constant Constant Expressions consist of 15
expressions only constant values. 20+5/2.0
'x'
Integral Integral Expressions are those m
Expressions which produce integer results. m*n-5
m* 'x'
5 + int (2.0)
where m and n are
integer variables.
Float Float Expressions are those which, x+y
expressions produce floating-point results. x * y/ 10
5 + float (10)
10.75
where x and y are
floating-point
variables. Ex
Pointer Pointer Expressions Pointer &m
Expressions Expressions produce address ptr
values. ptr +1
where m is a
variable and ptr is a
pointer.
Relational Relational Expressions results true x <= y
Dept of CSE Vanitha G P
Introduction to c++ programming Module 2 notes
Expressions or false as a result. a+b == c+d
m+n > 100
Logical Logical Expressions combine two
Expressions or more relational expressions and a>b && x==10
produces bool tyре(true or false) x==10 || y==5
results.
Bitwise Bitwise Expressions are used to x << 3 // Shift three
Expressions manipulate data at bit level. bit position to left
y >> 1 // Shift one
bit position to right
Special Assignment Expressions
[Link] Assignment:
x = (y = 10);
or
x = y = 10;
First 10 is assigned to y and then to x.
[Link] Assignment
x = (y = 50) +10;
(y = 50) is an assignment expression known as embedded assignment. Here,
the value 50 is assigned to y and then the result 50+10 = 60 is assigned to x.
This statement is identical to
y 50;
x = y + 10;
Compound Assignment
compound assignment operator which is a combination of the assignment
operator with a binary arithmetic operator.
x=x+ 10;
can be written as
Dept of CSE Vanitha G P
Introduction to c++ programming Module 2 notes
x += 10;//+= shorthand operator
Function prototyping
A function prototype in C++ is a declaration of a function's name, return type,
and parameters before its actual definition.
It informs the compiler about the function's existence and signature, allowing
it to verify function calls before encountering the full function definition.
Syntax:
returnType functionName(parameterType1, parameterType2, ...);
eg:
#include <iostream>
using namespace std
// Function prototype
int add(int, int);
int main() {
int sum = add(5, 3); // Calling the function before definition
cout << "The sum is: " << sum << std::endl;
return 0;
}
// Function definition
int add(int a, int b) {
return a + b;
}
Dept of CSE Vanitha G P
Introduction to c++ programming Module 2 notes
In this example, the int add(int, int); line is the function prototype. It tells the
compiler that a function named add exists, takes two integer arguments, and
returns an integer value. This allows the main function to call add before its
actual definition.
Call by references:
Call by reference in C++ is a method of passing arguments to a function where
the memory address of the variable is passed instead of its value. This allows
the function to directly modify the original variable. To achieve this, references
are used, which are aliases or alternative names for variables.
Example
#include <iostream>
using namespace std;
void swap(int &x, int &y) {
int temp = x;
x = y;
y = temp;
}
int main() {
int a = 10;
int b = 20;
cout << "Before swap: a = " << a << ", b = " << b << endl;
swap(a, b);
cout << "After swap: a = " << a << ", b = " << b << endl;
return 0;
}
Dept of CSE Vanitha G P
Introduction to c++ programming Module 2 notes
In the swap function, x and y are references to the
variables a and b in main. When swap is called, it operates directly on the
memory locations of a and b, thus changing their values.
Return by Reference
Function returns reference variable to called function.
Syntax:
dataType& functionName(parameters);
where,
datatype is the return type of the function(& represents reference variable),
and parameters are the passed arguments to it.
// C++ program to illustrate return
// by reference
#include <iostream>
using namespace std;
// Global variable
int x;
// Function returns as a return by reference
int& retByRef()
{
return x;
}
int main()
Dept of CSE Vanitha G P
Introduction to c++ programming Module 2 notes
{
// Function Call for return by reference
retByRef() = 10;
// Print X
cout << x;
return 0;
}
Return type of the above function retByRef() is a reference of the variable x so
value 10 will be assigned into the x.
Inline Functions
An inline function is a function where the compiler replaces the function call
with the actual code of the function body at the point of the call, rather than
performing a traditional function call.
This can improve performance by reducing the overhead associated with
function calls, such as stack operations, branching and saving registers.
Example:
inline int add(int a, int b) // inline function
{
return a + b;
}
int main() {
int result = add(5, 3); // The compiler may replace this with: int result = 5 + 3;
return 0;
}
Dept of CSE Vanitha G P
Introduction to c++ programming Module 2 notes
#include <iostream>
using namespace std;
// Inline function
inline int square(int x) {
return x * x;
}
int main() {
int num = 5;
// Calling inline function
int res = square(num);
cout << res;
return 0;
}
Dept of CSE Vanitha G P
Introduction to c++ programming Module 2 notes
The compiler may not perform inlining in the following cases:
1. If a function contains a loop.
2. If a function contains static variables.
3. If a function is recursive.
4. If a function return type is other than void, and the return statement
doesn’t exist in a function body.
5. If a function contains a switch or goto statement.
Advantages
Function call overhead doesn’t occur.
An inline function may be useful (if it is small) because an inline function
can yield less code than normal function call.
Disadvantages
Increased code size:
Dept of CSE Vanitha G P
Introduction to c++ programming Module 2 notes
The code of an inline function is inserted directly into the calling code at
compile time. If the function is large or called frequently, this can lead to
thrash.
Increased compilation time:
The compiler has to process and insert the code for each inline function call,
which can increase compilation time, especially in large projects with
numerous inline functions.
Not suitable for all functions:
Inline functions are not effective for recursive functions or functions
containing static variables. The compiler might ignore the inline keyword in
such cases.
Default arguments
C++ allows us to call a function without specifying all its arguments. In such
cases, the function assigns a default value to the parameter which does not
have a matching argument in the function call.
Eg: float amount(float principal,int period, float rate=0.15);
The above prototype declares a default value of 0.15 to the argument rate.
function call like value = amount (5000,7); // one argument missing
passes the value of 5000 to principal and 7 to period and then lets the
function use default value of 0.15 for rate.
#include<iostream>
using namespace std;
Float Simple_interest(float p,float t,float r=8.5)// r is a default argument
{
Float SI=(p*t*r)/100;
return(SI);
}
int main()
{
Dept of CSE Vanitha G P
Introduction to c++ programming Module 2 notes
Float amount=10000,time=5,result;
result= Simple_interest(amount,time);
//takes default value fo3rdparameter
Cout<<”simple interest with default rate of interest”<<result;
result= Simple_interest(amount,time,7.5); //r value will be 7.5
cout<<” simple interest with given rate of interest”<<result;
return 0;
}
Function Overloading:
Function overloading in C++ allows multiple functions with the same name to
be defined with parameter lists are different. This difference can be in the
number of parameters, the data types of parameters, or both. The return type
of the functions can be the same or different but it does not play a role in
function overloading.
#include <iostream>
Using namespace std;
int add(int a, int b) {
return a + b;
}
double add(double a, double b) {
return a + b;
}
Dept of CSE Vanitha G P
Introduction to c++ programming Module 2 notes
int add(int a, int b, int c) {
return a + b + c;
}
int main() {
cout << add(2, 3) << endl; // Calls add(int, int)
cout << add(2.5, 3.5) << endl; // Calls add(double, double)
cout << add(1, 2, 3) << endl; // Calls add(int, int, int)
return 0;
}
The compiler determines which overloaded function to be call based on
the arguments passed during the function call.
Function overloading enhances code readability and reusability by
allowing the same function name to be used for similar operations on
different data types or with varying numbers of arguments.
Dept of CSE Vanitha G P
Introduction to c++ programming Module 2 notes
Question bank
1. What are tokens in C++?explain with suitable examples
2. Define expression in C++ also explain its types.
3. Write a note on different assignments in c++.
4. What is the application of the scope resolution operator :: in C+
+ with an example?
5. What are the advantages of function prototypes in C++?
6. Describe the different styles of writing prototypes.
7. Find errors, if any, in the following function prototypes.
a. float average(x,y);
b. int mul(int a,b);
c. int display(...);
d. void Vect(int? &V, int & size);
e. void print(float data [, size = 20);
8. What is the main advantage of passing arguments by
reference? When will you make a function inline? Why?
9. How does an inline function differ from a preprocessor macro?
When do we need to use default arguments in a function?
[Link] c++ program to swap two numbers with pass by reference
technique.
(note : refer previous year questions along with question bank)
Dept of CSE Vanitha G P