0% found this document useful (0 votes)
23 views26 pages

C++ Module 1

C++ notes for engineering

Uploaded by

saicharanrolex
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
23 views26 pages

C++ Module 1

C++ notes for engineering

Uploaded by

saicharanrolex
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 26

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
In this tutorial, we will focus mostly on user-defined functions.

C++ User-defined Function


C++ allows the programmer to define their own function.

A user-defined function groups 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 {}

Note: We will learn about returnType and parameters later in this tutorial.

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();
}

How Function works in


C++

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;
}
Run Code

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() {
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;
}
Run Code

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.

C++
function with parameters

Note: The type of the arguments passed while calling the function must
match with the corresponding parameters defined in the function
declaration.
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.

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.

Example 3: 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;
}
Run Code

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.
Working of
C++ Function with return statement
Notice that sum is a variable of int type. This is because the return value
of add() is of int type.

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, ...);

Example 4: 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
int add(int a, int b) {
return (a + b);
}
Run Code

Output

100 + 78 = 178

The above program is nearly identical to Example 3. The only difference is


that here, the function is defined after the function call.
That's why we have used a function prototype in this example.

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.

Example 5: C++ Program to Find the Square Root of


a Number
#include <iostream>
#include <cmath>
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;
}
Run Code

Output

Square root of 25 = 5

In this program, the sqrt() library function is used to calculate the square root
of a number.
The function declaration of sqrt() is defined in the cmath header file. That's
why we need to use the code #include <cmath> to use the sqrt() function.
Call by Value, Call by Reference, and Call by
Address in C++
1. Home>
2. C++ Tutorials>
3. Call by Value, Call by Reference, and Call by Address in C++
Summary: In this tutorial, we will learn the difference between call by
value, call by reference, and call by address in the C++ programming
language.
To understand the importance of each type of call and their difference, we
must know, what the actual and formal parameters are:

Actual Parameters are the parameters that appear in the function call
statement.
Formal Parameters are the parameters that appear in the declaration of
the function which has been called.

Now let’s look at how each call mechanism works.

Call by Value

When a function is called in the call by value, the value of the actual
parameters is copied into formal parameters.
Both the actual and formal parameters have their own copies of values,
therefore any change in one of the types of parameters will not be reflected
by the other.

This is because both actual and formal parameters point to different


locations in memory (i.e. they both have different memory addresses).
Call by value method is useful when we do not want the values of the
actual parameters to be changed by the function that has been invoked.

C++ Example implementing Call by Value

#include <iostream>
using namespace std;

//Value of x gets copied into a


void increment(int a){
a++;
cout << "Value in Function increment: "<< a <<endl;
}

int main()
{
int x = 5;
increment(x);
cout << "Value in Function main: "<< x <<endl;
return 0;
}
Output:
Note the output of the program. The value of ‘a’ has been increased to 6,
but the value of ‘x’ in the main method remains the same.

This proves that the value is being copied to a different memory location in
the call by value.

Call by Reference

In the call by reference, both formal and actual parameters share the
same value.
Both the actual and formal parameter points to the same address in the
memory.

That means any change on one type of parameter will also be reflected by
other.

Calls by reference are preferred in cases where we do not want to make


copies of objects or variables, but rather we want all operations to be
performed on the same copy.

C++ Example implementing Call by Reference

#include <iostream>
using namespace std;

//Value of x is shared with a


void increment(int &a){
a++;
cout << "Value in Function increment: "<< a <<endl;
}

int main()
{
int x = 5;
increment(x);
cout << "Value in Function main: "<< x <<endl;
return 0;
}
Output:

Note: For creating reference, the ‘&‘ operator is used in preceding of


variable name.
Note the output in this case. The value of ‘a’ is increased to 6, the value of
‘x’ in the main also changes to 6.

This proves that changes made to formal parameters are also reflected by
the actual parameters as they share the same memory address space.

Call by Address

In the call by address method, both actual and formal parameters


indirectly share the same variable.
In this type of call mechanism, pointer variables are used as formal
parameters.
The formal pointer variable holds the address of the actual parameter,
hence the changes done by the formal parameter is also reflected in the
actual parameter.
As demonstrated in the diagram, both parameters point to different
locations in memory, but since the formal parameter stores the address of
the actual parameter, they share the same value.

C++ Example implementing Call by Address

#include <iostream>
using namespace std;

//a stores the address of x


void increment(int *a){
(*a)++;
cout << "Value in Function increment: "<< *a <<endl;
}

int main()
{
int x = 5;
increment(&x); //Passing address of x
cout << "Value in Function main: "<< x <<endl;
return 0;
}
Output:
The output here is the same as in the case of call by reference i.e. the
value of both ‘a’ and ‘x’ changes.

It is clear that changes made by the formal parameters are also changes
the actual parameter value.

Conclusion

As a conclusion, we can say that call by value should be used in cases


where we do not want the value of the actual parameter to be disturbed by
other functions and call by reference and call by address should be used in
cases where we want to maintain a variable or a copy of the object
throughout the program.

Hope you understood the different type of call mechanism in the C++
programming language. Comment below if you have any doubts.

Return by reference in C++ with Examples


Last Updated : 01 Aug, 2020
·
·
·
Pointers and References in C++ held close relation with one another. The
major difference is that the pointers can be operated on like adding values
whereas references are just an alias for another variable.
· Functions in C++ can return a reference as it’s returns a pointer.
· When function returns a reference it means it returns
a implicit pointer.
Return by reference is very different from Call by reference. Functions
behaves a very important role when variable or pointers are returned as
reference.
See this function signature of Return by Reference Below:
dataType& functionName(parameters);
where,
dataType is the return type of the function,
and parameters are the passed arguments to it.
Below is the code to illustrate the Return by reference:

· CPP

// C++ program to illustrate return by reference


#include <iostream>
using namespace std;
// Function to return as return by reference
int& returnValue(int& x)
{

// Print the address


cout << "x = " << x
<< " The address of x is "
<< &x << endl;

// Return reference
return x;
}

// Driver Code
int main()
{
int a = 20;
int& b = returnValue(a);

// Print a and its address


cout << "a = " << a
<< " The address of a is "
<< &a << endl;

// Print b and its address


cout << "b = " << b
<< " The address of b is "
<< &b << endl;

// We can also change the value of


// 'a' by using the address returned
// by returnValue function

// Since the function returns an alias


// of x, which is itself an alias of a,
// we can update the value of a
returnValue(a) = 13;

// The above expression assigns the


// value to the returned alias as 3.
cout << "a = " << a
<< " The address of a is "
<< &a << endl;
return 0;
}

Output:
x = 20 The address of x is 0x7fff3025711c
a = 20 The address of a is 0x7fff3025711c
b = 20 The address of b is 0x7fff3025711c
x = 20 The address of x is 0x7fff3025711c
a = 13 The address of a is 0x7fff3025711c
Explanation:
Since reference is nothing but an alias(synonym) of another variable, the
address of a, b and x never changes.
Note: We should never return a local variable as a reference, reason
being, as soon as the functions returns, local variable will be erased,
however, we still will be left with a reference which might be a security
bug in the code.
Below is the code to illustrate the Return by reference:

· C++

// 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;
}

// Driver Code
int main()
{
// Function Call for return
// by reference
retByRef() = 10;

// Print X
cout << x;
return 0;
}

Output:
10
Explanation:
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
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;
}
Run Code

Output
5
8
666

Here is how this program works:

Working of inline functions in C++


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.

C++ Programming Default


Arguments (Parameters)
In C++ programming, we can provide default values
for function parameters.
If a function with default arguments is called without passing arguments,
then the default parameters are used.

However, if arguments are passed while calling the function, the default
arguments are ignored.
Working of default arguments

How default arguments work in C++


We can understand the working of default arguments from the image
above:

1. When temp() is called, both the default parameters are used by the
function.
2. When temp(6) is called, the first argument becomes 6 while the default
value is used for the second parameter.
3. When temp(6, -2.3) is called, both the default parameters are
overridden, resulting in i = 6 and f = -2.3.
4. When temp(3.4) is passed, the function behaves in an undesired way
because the second argument cannot be passed without passing the
first argument.

Therefore, 3.4 is passed as the first argument. Since the first


argument has been defined as int, the value that is actually passed
is 3.

Example: Default Argument


#include <iostream>
using namespace std;

// defining the default arguments


void display(char = '*', int = 3);

int main() {
int count = 5;

cout << "No argument passed: ";


// *, 3 will be parameters
display();

cout << "First argument passed: ";


// #, 3 will be parameters
display('#');

cout << "Both arguments passed: ";


// $, 5 will be parameters
display('$', count);

return 0;
}

void display(char c, int count) {


for(int i = 1; i <= count; ++i)
{
cout << c;
}
cout << endl;
}
Run Code

Output

No argument passed: ***


First argument passed: ###
Both arguments passed: $$$$$

Here is how this program works:

1. display() is called without passing any arguments. In this


case, display() uses both the default parameters c = '*' and n = 1.
2. display('#') is called with only one argument. In this case, the first
becomes '#'. The second default parameter n = 1 is retained.
3. display('#', count) is called with both arguments. In this case, default
arguments are not used.
We can also define the default parameters in the function definition itself.
The program below is equivalent to the one above.

#include <iostream>
using namespace std;

// defining the default arguments


void display(char c = '*', int count = 3) {
for(int i = 1; i <= count; ++i) {
cout << c;
}
cout << endl;
}

int main() {
int count = 5;

cout << "No argument passed: ";


// *, 3 will be parameters
display();
cout << "First argument passed: ";
// #, 3 will be parameters
display('#');

cout << "Both argument passed: ";


// $, 5 will be parameters
display('$', count);

return 0;
}
Run Code

Things to Remember
1. Once we provide a default value for a parameter, all subsequent
parameters must also have default values. For example,

2. // Invalid
3. void add(int a, int b = 3, int c, int d);
4.
5. // Invalid
6. void add(int a, int b = 3, int c, int d = 4);
7.
8. // Valid

void add(int a, int c, int b = 3, int d = 4);

9. If we are defining the default arguments in the function definition


instead of the function prototype, then the function must be defined
before the function call.

10. // Invalid code


11.
12. int main() {
13. // function call
14. display();
15. }
16.
17. void display(char c = '*', int count = 5) {
18. // code

You might also like