C++ Unit-Ii

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

riteshkandarics@gmail.

com iamriteshkandari 9259069231

UNIT II:

C++ Functions
A function is a block of code that performs a specific task.
Suppose we need to create a program to create a circle and color it. We can create two functions
to solve this problem:
• a function to draw the circle
• a function to color the circle
Dividing a complex problem into smaller chunks makes our program easy to understand and
reusable.
There are two types of function:
1. Standard Library Functions: Predefined in C++
2. User-defined Function: Created by users

C++ User-defined Function


C++ allows the programmer to define their own function.
A user-defined function group’s code to perform a specific task and that group of code is given
a name (identifier).
When the function is invoked from any part of the program, it all executes the codes defined
in the body of the function.

C++ Function Declaration


The syntax to declare a function is:
returnType functionName (parameter1, parameter2,...)
{
// function body
}
Here's an example of a function declaration.
// function declaration
void greet()
{
cout << "Hello World";
}
Here,
• the name of the function is greet()
• the return type of the function is void
• the empty parentheses mean it doesn't have any parameters
• the function body is written inside {}
[email protected] iamriteshkandari 9259069231

Calling a Function
In the above program, we have declared a function named greet(). To use the greet() function,
we need to call it.
Here's how we can call the above greet() function.
int main()
{
// calling a function
greet();
}
Example 1: Display a Text
#include <iostream>
using namespace std;
// declaring a function
void greet() {
cout << "Hello there!";
}
int main() {
// calling the function
greet();
return 0;
}
Output
Hello there!

Function Parameters
As mentioned above, a function can be declared with parameters (arguments). A parameter is
a value that is passed when declaring a function.
For example, let us consider the function below:
void printNum(int num)
{
cout << num;
}
Here, the int variable num is the function parameter.

We pass a value to the function parameter while calling the function.


int main()
{
[email protected] iamriteshkandari 9259069231
int n = 7;
// calling the function
// n is passed to the function as argument
printNum(n);
return 0;
}

Example 2: Function with Parameters


// program to print a text

#include <iostream>
using namespace std;
// display a number
void displayNum(int n1, float n2) {
cout << "The int number is " << n1;
cout << "The double number is " << n2;
}
int main()
{
int num1 = 5;
double num2 = 5.5;
// calling the function
displayNum(num1, num2);
return 0;
}
Output
The int number is 5
The double number is 5.5
In the above program, we have used a function that has one int parameter and
one double parameter.
We then pass num1 and num2 as arguments. These values are stored by the function
parameters n1 and n2 respectively.

Return Statement
In the above programs, we have used void in the function declaration. For example,
void displayNumber()
{
// code
}
This means the function is not returning any value.
[email protected] iamriteshkandari 9259069231
It's also possible to return a value from a function. For this, we need to specify
the returnType of the function during function declaration.
Then, the return statement can be used to return a value from a function.
For example,
int add (int a, int b) {
return (a + b);
}
Here, we have the data type int instead of void. This means that the function returns
an int value.
The code return (a + b); returns the sum of the two parameters as the function value.
The return statement denotes that the function has ended. Any code after return inside the
function is not executed.

Add Two Numbers


// program to add two numbers using a function
#include <iostream>
using namespace std;
// declaring a function
int add(int a, int b) {
return (a + b);
}
int main() {
int sum;
// calling the function and storing
// the returned value in sum
sum = add(100, 78);
cout << "100 + 78 = " << sum << endl;
return 0;
}
Output
100 + 78 = 178
In the above program, the add() function is used to find the sum of two numbers.
We pass two int literals 100 and 78 while calling the function.
We store the returned value of the function in the variable sum, and then we print it.

Notice that sum is a variable of int type. This is because the return value of add() is of int type.
[email protected] iamriteshkandari 9259069231

Function Prototype
In C++, the code of function declaration should be before the function call. However, if we
want to define a function after the function call, we need to use the function prototype. For
example,
// function prototype
void add(int, int);
int main() {
// calling the function before declaration.
add(5, 3);
return 0;
}
// function definition
void add(int a, int b) {
cout << (a + b);
}
In the above code, the function prototype is:
void add(int, int);
This provides the compiler with information about the function name and its parameters. That's
why we can use the code to call a function before the function has been defined.
The syntax of a function prototype is:
returnType functionName(dataType1, dataType2, ...);

C++ Function Prototype


// using function definition after main() function
// function prototype is declared before main()
#include <iostream>
using namespace std;
// function prototype
int add(int, int);
int main() {
int sum;
// calling the function and storing
// the returned value in sum
sum = add(100, 78);
cout << "100 + 78 = " << sum << endl;
return 0;
}

// function definition
[email protected] iamriteshkandari 9259069231
int add(int a, int b) {
return (a + b);
}
Output
100 + 78 = 178

Benefits of Using User-Defined Functions


• Functions make the code reusable. We can declare them once and use them multiple
times.
• Functions make the program easier as each small task is divided into a function.
• Functions increase readability.

C++ Library Functions


Library functions are the built-in functions in C++ programming. Programmers can use library
functions by invoking the functions directly; they don't need to write the functions themselves.
Some common library functions in C++ are sqrt(), abs(), isdigit(), etc. In order to use library
functions, we usually need to include the header file in which these library functions are
defined. For instance, in order to use mathematical functions such as sqrt() and abs(), we need
to include the header file cmath.

C++ Program to Find the Square Root of a Number


#include <iostream>
#include <math.h>
using namespace std;
int main() {
double number, squareRoot;
number = 25.0;
// sqrt() is a library function to calculate the square root
squareRoot = sqrt(number);
cout << "Square root of " << number << " = " << squareRoot;
return 0;
}
Output
Square root of 25 = 5
In this program, the sqrt() library function is used to calculate the square root of a number.
[email protected] iamriteshkandari 9259069231

Call by value and call by reference in C++


There are two ways to pass value or data to function in C language: call by value and call by
reference. Original value is not modified in call by value but it is modified in call by reference.

Call by value in C++

In call by value, original value is not modified.


In call by value, value being passed to the function is locally stored by the function parameter
in stack memory location. If you change the value of function parameter, it is changed for the
current function only. It will not change the value of variable inside the caller method such as
main().
Let's try to understand the concept of call by value in C++ language by the example given
below:
#include <iostream>
using namespace std;
void change(int data);
int main()
{
int data = 3;
change(data);
cout << "Value of the data is: " << data<< endl;
return 0;
}
void change(int data)
{
data = 5;
}
Output:
Value of the data is: 3

Call by reference in C++

In call by reference, original value is modified because we pass reference (address).


Here, address of the value is passed in the function, so actual and formal arguments share the
same address space. Hence, value changed inside the function, is reflected inside as well as
outside the function.
Note: To understand the call by reference, you must have the basic knowledge of pointers.
[email protected] iamriteshkandari 9259069231
Let's try to understand the concept of call by reference in C++ language by the example given
below:
#include<iostream>
using namespace std;
void swap(int *x, int *y)
{
int swap;
swap=*x;
*x=*y;
*y=swap;
}
int main()
{
int x=500, y=100;
swap(&x, &y); // passing value to function
cout<<"Value of x is: "<<x<<endl;
cout<<"Value of y is: "<<y<<endl;
return 0;
}
Output:
Value of x is: 100
Value of y is: 500

Difference between Call by Value and Call by reference in C++

No. Call by value Call by reference


1 A copy of value is passed to the An address of value is passed to the function
function
2 Changes made inside the function is Changes made inside the function is reflected
not reflected on other functions outside the function also
3 Actual and formal arguments will be Actual and formal arguments will be created
created in different memory location in same memory location
[email protected] iamriteshkandari 9259069231

C++ Inline Functions

In C++, we can declare a function as inline. This copies the function to the location of the
function call in compile-time and may make the program execution faster.

Inline Functions
To create an inline function, we use the inline keyword. For example,
inline returnType functionName(parameters) {
// code
}
Notice the use of keyword inline before the function definition.

C++ Inline Function


#include <iostream>
using namespace std;
inline void displayNum(int num)
{
cout << num << endl;
}
int main()
{
// first function call
displayNum(5);
// second function call
displayNum(8);
// third function call
displayNum(666);
return 0;
}

Output
5
8
666
Here is how this program works:
[email protected] iamriteshkandari 9259069231

Here, we created an inline function named displayNum() that takes a single integer as a
parameter.
We then called the function 3 times in the main() function with different arguments. Each
time displayNum() is called, the compiler copies the code of the function to that call location.

You might also like