Difference Between Call By Value and Call By Reference in C++

In C++ programming, there are two ways of passing value to the function: Call by Value or Call by Reference


Before going further into this topic, I will suggest you understand the difference between actual parameters and formal parameters. The actual parameters are those parameters that are passed to the function and formal parameters are those parameters that are received by the function.


Call by Value: Here the values of actual parameters will be copied to formal parameters and these two different parameters store values in different memory locations. Any changes made to the variable inside function are not going to reflect back to the actual parameter. 

Example:

//C++ Example of call by value
#include<iostream>
using namespace std;

//function definition
void update(int x, int y){

   x = 5;
   y = 40;
   cout<<"Values inside function call:"<<endl;
   cout<<"x = "<<x<<endl;
   cout<<"y = "<<y<<endl;
}
int main(){

    int x = 10, y = 20;    
    
    //function call
    update(x, y);
    cout<<"Values after function call:"<<endl;
    cout<<"x = "<<x<<endl;
    cout<<"y = "<<y<<endl; 

    return 0;
}
Output:
Values inside function call:
x = 5
y = 40
Values after function call:
x = 10
y = 20

call by value example

Here in the above code, we have updated the value of x and y inside the function but that is not affecting the value of our original variable x and y inside the main() function. It is happening because variables inside update() are local to the function and get destroyed later. 


Call by Reference: Here both actual and formal parameters refer to the same memory location. Therefore, any changes made to the formal parameters will get reflected in the actual parameters. 
In Call by Reference, instead of passing values to the function we are passing the memory addresses at which those values are stored using the address of operator (&). The parameters of function are pointers that is used to hold the address of another variable(alert-success)
Example:
//C++ Example of call by reference
#include<iostream>
using namespace std;

//function definition
void update(int *x, int *y){

   *x = 50;
   *y = 40;
   cout<<"Values inside function call:"<<endl;
   cout<<"x = "<<*x<<endl;
   cout<<"y = "<<*y<<endl;
}
int main(){

    int x = 10, y = 20;    
    
    //function call
    update(&x, &y);
    cout<<"Values after function call:"<<endl;
    cout<<"x = "<<x<<endl;
    cout<<"y = "<<y<<endl; 

    return 0;
}
Output:
Values inside function call:
x = 50
y = 40
Values after function call:
x = 50
y = 40

call by reference
Here in the above code, we are passing the address of the variable &x and &y to the function update() and the parameters of this function are pointers (*x and *y). A pointer is used to hold the address of another variable and you can fetch the value present at that particular address using dereference operator (*).  

Difference Between Call by Value and Call by Reference.

Call By Value Call By Reference
Copies of arguments are passed to the function. Changes to parameters inside the function do not affect the original values. References to the original arguments are passed to the function. Changes to parameters inside the function directly affect the original values.
Syntax: void functionName(int a, int b) Syntax: void functionName(int &a, int &b)
Changes inside the function do not affect the original variables. Changes inside the function directly affect the original variables.
May have a performance impact if large data structures are passed since copies are made. Typically more efficient as no copies are made, especially for large data structures.
// Call By Value Example
void swap(int x, int y) {
int temp = x; x = y;
y = temp;
}
int main() {
int a = 5, b = 10;
swap(a, b); cout << "a: " << a << ", b: " << b;
return 0;
}
// Call By Reference Example
void swap(int &x, int &y) {
int temp = x; x = y; y = temp;
}
int main() {
int a = 5, b = 10; swap(a, b); cout << "a: " << a << ", b: " << b;
return 0;
}


Read more:

Types of Functions in C++

In C++ programming, you can categorize functions into four different categories based on the arguments we are passing to the function and the return type of the function. These are:

  • Function with no argument and no return type value.
  • Function with argument but no return type value.
  • Function with no argument but with return type value.
  • Function with argument and with return type value.

1. Function with no argument and no return type value.

In this type of function, we do not pass any value while calling the function and no value is returned from the function as an output.

Example:

#include<iostream>
using namespace std;

//function with no argument and no return type
void sum(){

    int x = 10, y = 5, z = 8;
    int sum = x + y + z;
    cout<<"Total Sum = "<<sum;
}
int main(){
    //function call
    sum();

    return 0;
}
Output:
Total Sum = 23

Here in the above code, the sum() function is called inside main() without any arguments. The sum() function performs the summation of three variable x, y, and z, and print the answer. As the return type of sum() is void so no value is returned by the function.

2. Function with argument but no return type value.

In this type of function, we do pass values while calling the function but no value is returned from the function as an output.

Example:
#include<iostream>
using namespace std;

//function with argument but no return type
void sum(int x, int y, int z){

    int sum = x + y + z;
    cout<<"Total Sum = "<<sum;
}
int main(){
    int a = 10, b = 3, c = 9;
    //function call
sum(a, b, c); return 0; }
Output:
Total Sum = 22

Here in the above code, the sum() function is called inside main() with three arguments a, b, and c, and the sum() function performs the addition of the three values and prints the total sum. The return type of the function sum() is void so no value is returned by the function.

3. Function with no argument but with return type value.

In this type of function, we do not pass values while calling the function but some value is returned from the function as an output. 

Example:
#include<iostream>
using namespace std;

//function with no argument but return type
int sum(){

    int x = 10, y = 8, z = 15, sum;
    sum = x + y + z;
    return sum;
}
int main(){
        
    //function call
    int answer = sum();
    cout<<"Total Sum = "<<answer;
    return 0;
}
Output:
Total Sum = 33

Here in the above code, the sum() function is called inside the main() function with no arguments, and the sum() function perform the addition of value x, y, and z and return the sum value. 

4. Function with argument and with return type value.

In this type of function, we do pass values while calling the function and some value is returned from the function as an output. 

Example: 
#include<iostream>
using namespace std;

//function with argument and with return type
int sum(int x, int y){

    int sum;
    sum = x + y;
    return sum;
}
int main(){

    int m = 10, n = 20;    
    //function call
    int answer = sum(m , n);
    cout<<"Total Sum = "<<answer;
    return 0;
}
Output:
Total Sum = 30

Here in the above, the sum() is called inside main() with two arguments m and n, and sum() adds those two values and returns the value of sum which is an integer. type.

Based on your requirement and condition you can choose any method out of four to solve your problem.

Read next:

Difference between Argument and Parameter.

The two terms Parameters and Arguments are often used interchangeably while working on functions in programming but both the term have totally different meanings let's understand the difference between them.

Parameters

A Parameter is a variable in the declaration and definition of the function. The value of these variables is used inside the function to perform some computation on it and return us some output. The parameter is also known as Format Parameter.  

Example:
//C++ Example for Parameters
#include<iostream>
using namespace std;

//function definition
//x and y are two parameters
int add(int x, int y){
    return (x + y);
}
int main(){

    int m = 22, n = 8, sum;
    //function call
    sum = add(m, n);
    cout<<"SUM = "<<sum;

    return 0;
}
Output:
SUM = 30

Here add() function is defined with two parameters x and y and this function is used to perform addition of two numbers.

Arguments

Argument is a actual value of the parameter that gets passed to the function when the function is called.These values are passed to the function at the time of function call. They are also called as Actual Parameter.

Example:
//C++ Example for Arguments
#include<iostream>
using namespace std;

//function definition
int sub(int x, int y){
    return (x - y);
}
int main(){

    int m = 20, n = 8, diff;
    //function call
    //m and n are two arguments
    diff = sub(m, n);
    cout<<"Difference = "<<diff;

    return 0;
}
Output:
Difference = 12

Here sub() function is called with two argument value m and n and the task of this function is to perform the substraction of two numbers.


How To Fix Implicit Declaration of function Error?

In the previous post, we discussed functions in detail and here in this post, we are going to discuss one error that we often encounter while working with functions which is the "implicit declaration of function". 


The implicit declaration function error is encountered when you use (or call) the function before declaring or defining it. It is because the compiler has no information about that function at the time of calling it so the compiler implicitly assumes something about the function.

Example:

//C++ Implicit Declaration of function
#include<iostream>
using namespace std;

int main(){
    
    int m = 6, n = 8;
    //function call
    int greater = find(m, n);
    cout<<"Greater number is: "<<greater;

    return 0;
}
//function definition
int find(int x, int y){

    if(x < y){
        return y;
    }
    else{
        return x;
    }
}
Output:
../src/main.c:48:9: error: implicit declaration of function 'find' [-Werror=implicit-function-declaration]
         find();
Here the find() function is not declared before calling inside the main function and the definition of the function is written after the main function so when it is called inside the main function the compiler has no information about the find() function and gives us an error message. (alert-warning)

How Execution takes place in C++?

Before understanding the solution for the above error it is important to understand how execution takes place in C++ Programming. 

If you are familiar with C++ programming you must have heard that execution starts from the global function main() but it is partially correct. The compiler starts the execution of the program from the first statement and all statements are executed one by one from top to bottom. Even if you have defined any function before or after the main then also the flow of execution will remain the same, but the statements inside the function get executed only when that function is called. 

How to resolve Implicit Declaration of Function Error?

There are two ways to resolve this error:
  • If you define the function before the main function then you only have to define it and you don't have to separately declare or define it. 
Example:  
//C++ Example program to find greater
#include<iostream>
using namespace std;

//function definition before using it
int find(int x, int y){

    if(x < y){
        return y;
    }
    else{
        return x;
    }
}
int main(){
    
    int m = 6, n = 8;
    //function call
    int greater = find(m, n);
    cout<<"Greater number is: "<<greater;

    return 0;
}
Output:
Greater number is: 8

  • If you define a function after the main function then you have to put a matching declaration of that function before the main.
Example:

//C++ Example program to find greater
#include<iostream>
using namespace std;

//function declaration before using it
int find(int, int);

int main(){
    
    int m = 6, n = 8;
    //function call
    int greater = find(m, n);
    cout<<"Greater number is: "<<greater;

    return 0;
}
//function definition after main
int find(int x, int y){

    if(x < y){
        return y;
    }
    else{
        return x;
    }
}
Output:
Greater number is: 8

Here find() function is declared before the main function at the top but it is defined after the main function so the program will execute successfully because the compiler already knows about the find function from its declaration.

Functions in C++

A function is a set of statements that takes inputs, performs some computation, and produces output. The idea of creating a function is to put the repetitive blocks of code together and give a name. They are used to perform some specific task and instead of writing that block of code again and again you can call the function to perform that task. 

Syntax:
syntax of function
C++ Example: 
//C++ Example of a function
#include<iostream>
using namespace std;

//function definition to perform addition
int fun(int x, int y){
    
    int sum = x + y;

    return sum;
}

int main(){

    int a = 10, b = 20;
    //calling the function fun perform addition
    int sum = fun(a, b);
    cout<<"Sum: "<<sum;

    return 0;
}
Output:
Sum: 30
Note: A function without input parameters can also perform computation and return some output. (alert-success)

Why functions are used?

There are two important reasons why we are using functions:

  • Reusability: Once the function is defined, it can be reused over and over again. You can simply call the function everywhere in your program to perform that specific task. 
  • Abstraction: If you are just using the function in your program then you don't have to worry about how it works inside.

There are two types of functions:
  • Standard Library Functions: These are built-in functions that are already available in C++ programming language and you can directly use them in your code without worrying about the implementation part.
  • User-defined Functions: These are defined by the user based on their requirement to perform some specific task.
Here in this post, we are going to discuss user-defined functions in detail.


Function Declaration in C++.

A function declaration (also called function prototype) means declaring the properties of a function to the compiler. This property includes the name of the function, the return type of the function, the number of parameters, and its type. 
Note: It is not necessary to put the name of the parameter in function prototype. (alert-success) 
Example:

/*function taking two integers as 
parameter and returning an integer*/
int sum(int x, int y);

/*function taking one character as
parameter and returning a char*/
char fun(char ch);

/*function taking two-pointer variable
as a parameter and no return type*/
void sum(int*, int*);

/*function taking one integer and
one integer type pointer as a parameter
and return an integer type pointer*/
int* greater(int, int*);


Function Definition in C++.

A function definition consists of a block of code that is capable of performing some specific task. Let's understand this with an example:

Example:
//C++ Function example to add numbers
#include<iostream>
using namespace std;

//function declaration
int add(int, int);

int main(){
    
    int m = 5, n = 15, sum;
    //function call
    sum = add(m, n);
    cout<<"Sum = "<<sum;

    return 0;
}
//function definition
int add(int x, int y){
    return (x + y);
}
Output:
Sum: 20

Working of above function:
  • At first, we have declared the function "add" to have two integer type parameters and the function is going to return an integer type value. There is no need to mention the name of the variable. 
  • Inside the main function, we are calling the function "add" and pass the two arguments. You should not mention the data types of the argument or the return type of the function.
  • After the main function, we have defined our "add" function and here it is important to mention both the data type and the name of the parameters.


Error: Implicit Declaration of function

It is not necessary to declare the function before using but it is preferred to declare the function before using it. If you do not declare before using it then you will get an error "implicit declaration of function" because the compiler implicitly assumes something about the function. 
Error message:
../src/main.c:48:9: error: implicit declaration of function 'add' [-Werror=implicit-function-declaration]
         add();
You can resolve this error in two ways, declare the function before using it else define the function above the main function before calling it.


Switch Statement in C++ with Example

In C++ programming, the switch statement is used to execute one block of code out of multiple blocks of code.

Switch statement Syntax in C++.

switch (expression)
    {
    case /* constant-expression */:
        /* code */
        break;
    case /* constant-expression */:
        /* code */
        break;
    default:
         /*expression not matching with any constant-expression */
        /* code */
    }

Working of switch statement:
  • The switch expression is evaluated once and then compared with the constant-expression value of each case.
  • If the correct match is found, the associated code of that particular case is executed until the break statement in encountered. 
  • When there is no matching expression then default code block is executed.

Switch Statement Flowchart

switch statement flowchart
Switch Statement Flowchart

Example: This C++ program is printing the weekday based on the number.

//C++ Example switch statement
#include<iostream>
using namespace std;

int main(){

    int day;
    cout<<"Enter a day number: ";
    cin>>day;

    switch (day)
    {
    case 1:
        cout<<"Today is Monday";
        break;
    case 2:
        cout<<"Today is Tuesday";
        break;
    case 3:
        cout<<"Today is Wednesday";
        break;
    case 4:
        cout<<"Today is Thursday";
        break;
    case 5:
        cout<<"Today is Friday";
        break;
    case 6:
        cout<<"Today is Saturday";
        break;
    case 7:
        cout<<"Today is Sunday";
        break;                    
    default:
        cout<<"No match found";
    }
    
    return 0;
}
Output 1:
Enter a day number: 5
Today is Friday

Output 2:
Enter a day number: 9
No match found

Here in output 2, the default code block is executed because there is no matching constant-expression matching with value 9 in the switch case.


Use break keyword in switch.

The break statement is optional in switch and it is used to come out of switch block and ignore the execution of reset of the cases. If you don't mention break statement at the end of each switch case then compiler keep executing next case until it found a break statement. 

Example:
//C++ Example switch statement
#include<iostream>
using namespace std;

int main(){

    int day;
    cout<<"Enter a day number: ";
    cin>>day;

    switch (day)
    {
    case 2:
        cout<<"\nToday is Tuesday";
        break;
    case 3:
        cout<<"\nToday is Wednesday";
        /*break statement is missing here*/
    case 4:
        cout<<"\nToday is Thursday";
        break;
    case 7:
        cout<<"\nToday is Sunday";
        break;                    
    default:
        cout<<"\nNo match found";
    }
    
    return 0;
}
Output:
Enter a day number: 3

Today is Wednesday
Today is Thursday

Here in the output, you can observe that when we have selected a case not having a break statement then code executed the next block also and stop when it found a break statement. 

Note: You can perform the same task using if...else statement in C++ but in few cases switch case is use because it is more easy to read and understand. (alert-passed)


Few examples of switch case problem:

Break and Continue Statement in C++

In C++ programming, break and continue statements are used inside loops and switch statements to manipulate the normal execution of the loop and switch statements.

C++ Break Statement.

A break statement is used to bring the control of the program out of the loop. It is basically used to jump out of a running loop. 

syntax: break;


Flowchart of a break statement.

break statement flowchart
break statement Flowchart

Example:
//C++ Example of break statement
#include<iostream>
using namespace std;

int main(){

    cout<<"Print number using for loop"<<endl;
    for(int i = 0; i <= 10; i++){
        if(i == 5){
            break;
        }
        cout<<i<<" ";
    }

    int i = 1;
    
    cout<<"\nPrint number using while loop"<<endl;
    while(i <= 10){
        if(i == 4){
            break;
        }
        cout<<i<<" ";
        i++;
    }
    return 0;
}
Output:
Print number using for loop
1 2 3 4
Print number using while loop
1 2 3

Here in the above example, you can see that both the loop condition is written for printing value from 1 to 10 but both programs jump out of the loop as soon as the break condition is satisfied. 

C++ Continue statement.

The continue statement is used to skip the current iteration of the loop if the specified condition is true and continue with the next iteration of the loop. 
syntax: continue;

Flowchart of a continue statement.

continue flowchart
continue Flowchart
Example:
//C++ Example of continue statement
#include<iostream>
using namespace std;

int main(){

    for(int i = 1; i <= 10; i++){
        if(i == 5){
            continue;
        }
        cout<<i<<" ";
    }

    return 0;
}
Output:
1 2 3 4 6 7 8 9 10

Here, if you observe the output then you can see that value 5 is not printed by the loop because that condition is evaluated true for the continue statement so it skips the remaining part of the code and moves to the next iteration.

DON'T MISS

Tech News
© all rights reserved
made with by AlgoLesson