Actual purpose of int& foo() in C++

Hello, Coders!! In this section, we will discuss the actual purpose of int& foo() in a C++ program.

int& foo() in C++

In C++ int& foo() declares a function having a function named foo() of data type int&.

The foo() function of type int& returns a reference to an int instead of a int value. Likewise, we can declare the foo() with other data types as well.

We can say it is very much similar to the pointer, we are not actually returning values out of the function here instead, we are passing the reference needed to determine the address of that int.

Let’s understand it with examples.

Example1: Changing the global variable using int& foo()

Here, in this program, we will use int& foo() to return the reference to a global variable. The foo() will return an lvalue reference to a valid global int value.

int a = 10; // Declearing the global variable int& foo() { 

    return a; // It will return the refernce of the int a 
 }

Since foo() returns lvalue reference, we can change or assign a new value to the global variable.

foo() = 86;

By doing so, it will update the global variable with the assigned value. We can then check whether the change took place or not by simply accessing the variable directly.

int main() { 

cout << "Before: " << a <<endl; 
foo() = 86; 
cout << "After: " << a; 

}

Here is the complete program,

#include<iostream>

using namespace std;

int a = 10; // Declearing the global variable

int& foo() {
   return a; // It will return the refernce of the int a
}

int main() {

  cout << "Before: " << a <<endl;
  foo() = 86;
  cout << "After: " << a;
  
 return 0;
}

Output:

Before: 10
After: 86

Example2: Changing the static variable value using int& foo()

Declare int& foo() with a static integer variable var having a value. Since it is a static variable, it will live on even after the function call. Now return the reference to the variable var using the return keyword.

int& foo() {
  static int var = 10;
  return var;
}

Now will assign a new value to the static variable by using foo() since it returns the reference to  lvalue of the static int. In this case, we simply assign to the reference and the reference is nothing but an alias for the var.

foo() = 86;

Finally, we can check the changes by assessing or printing the foo().

int main() {
  cout << "Before" << foo() << endl;
  foo() = 86;
  cout << "After" << f00();
}

Here is the complete program;

#include<iostream>

using namespace std;

int& foo() {
   static int var = 10;
   return var; // It will return the refernce to the var
}

int main() {

  cout << "Before: " << foo() <<endl;
  foo() = 86;
  cout << "After: " << foo();
  
 return 0;
}

Output:

Before: 10
After: 86

Hope you have learned a new concept and use of the int& foo() in any C++ program.

Happy Coding!!!

You can also read, How to use void pointer in C++?

Leave a Reply

Your email address will not be published. Required fields are marked *