C++ const &

You may find the const & expression used in parameters list of a function. This expression is made up of const keyword and & operator. Now lets explore the uses of const and & operators in C++.

-const is a special keyword in C++. It is used to make a variable immutable (can not be changed) during the program execution.
Example:
const int count=100;
The variable count has its value of 100. This value can not be changed in the program.

-& operator is commonly used to pass parameters by reference in C++. When the parameters are passed by reference (addresses of parameters passed), the values of the parameters can be changed by the function in which they are passed to.
Example:
#include <cstdlib>
#include <iostream>
using namespace std;

int sum( int &a,int &b){
   //sum a and b
   int s=a+b;
   //change values of a and b
   a=100;
   b=200;
   return s;
}

int main(int argc, char *argv[])
{
   int a=10;
   int b=20;
   cout<<"Before passing: a="<<a<<",b="<<b<<"\n";
   cout<<"Sum of a and b:"<<sum(a,b)<<"\n";
   cout<<"After passing: a="<<a<<",b="<<b<<"\n";
   system("PAUSE");
   return EXIT_SUCCESS;
}



Now you understand the use of const keyword and & operator. What is the use of the two together? When const keyword and & operator are used together, the parameters are passed by reference. However, their address are read-only. When an address of a variable is read-only, you can not change the value of the variable. If you try to change it, you will get an error from compiler.
Example:

#include <cstdlib>
#include <iostream>

using namespace std;

int sum( int const &,int const &); //function sum header

int main(int argc, char *argv[])
{
   int a=10;
   int b=20;
   cout<<"Before passing: a="<<a<<",b="<<b<<"\n";
   cout<<"Sum of a and b:"<<sum(a,b)<<"\n";
   cout<<"After passing: a="<<a<<",b="<<b<<"\n";
   system("PAUSE");
   return EXIT_SUCCESS;
}
int sum( int const &a,int const &b){ //function sum body
   //sum a and b
   int s=a+b;
   //change values of a and b=> error
   a=100;
   b=200;
   return s;
}

Posted by: Ly | post date: 02-03-2013 | Subject: C++ Programming Language




This website intents to provide free and high quality tutorials, examples, exercises and solutions, questions and answers of programming and scripting languages:
C, C++, C#, Java, VB.NET, Python, VBA,PHP & Mysql, SQL, JSP, ASP.NET,HTML, CSS, JQuery, JavaScript and other applications such as MS Excel, MS Access, and MS Word. However, we don't guarantee all things of the web are accurate. If you find any error, please report it then we will take actions to correct it as soon as possible.