Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference of function argument as (const int &) and (int & a) in C++

I know that if you write void function_name(int& a), then function will not do local copy of your variable passed as argument. Also have met in literature that you should write void function_name(const int & a) in order to say compiler, that I dont want the variable passed as argument to be copied.

So my question: what is the difference with this two cases (except that "const" ensures that the variable passed will not be changed by function!!!)???

like image 666
Narek Avatar asked Apr 28 '10 07:04

Narek


2 Answers

You should use const in the signature whenever you do not need to write. Adding const to the signature has two effects: it tells the compiler that you want it to check and guarantee that you do not change that argument inside your function. The second effect is that enables external code to use your function passing objects that are themselves constant (and temporaries), enabling more uses of the same function.

At the same time, the const keyword is an important part of the documentation of your function/method: the function signature is explicitly saying what you intend to do with the argument, and whether it is safe to pass an object that is part of another object's invariants into your function: you are being explicit in that you will not mess with their object.

Using const forces a more strict set of requirements in your code (the function): you cannot modify the object, but at the same time is less restrictive in your callers, making your code more reusable.

void printr( int & i ) { std::cout << i << std::endl; }
void printcr( const int & i ) { std::cout << i << std::endl; }
int main() {
   int x = 10;
   const int y = 15;
   printr( x );
   //printr( y ); // passing y as non-const reference discards qualifiers
   //printr( 5 ); // cannot bind a non-const reference to a temporary
   printcr( x ); printcr( y ); printcr( 5 ); // all valid 
}
like image 127
David Rodríguez - dribeas Avatar answered Oct 09 '22 22:10

David Rodríguez - dribeas


So my question: what is the difference with this two cases (except that "const" enshures that the variable passes will not be changed by function!!!)???

That is the difference.

like image 32
Alex Budovski Avatar answered Oct 09 '22 21:10

Alex Budovski