Alex Rivera | Logout

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

Asked 2010-04-28T07:03:12.143
9

I know that if you write void function_name(int& a), then the 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 don't want the variable passed as argument to be copied.

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

Edit
Report

2 Answers

0

I would say that

void cfunction_name(const X& a);

allows me to pass a reference to temporary object as follows

X make_X();

function_name(make_X());

While

void function_name(X& a);

fails to achieve this. with the following error error: invalid initialization of non-const reference of type 'X&' from a temporary of type 'X'

answered 2010-04-28T07:46:27.373
0

leaving out the performance discussion, let the code speak!

void foo(){
    const int i1 = 0;
    int i2 = 0;
    i1 = 123; //i gets red -> expression must be a modifiyble value
    i2 = 123;
}
//the following two functions are OK
void foo( int i ) {
    i = 123;
}
void foo( int & i ) {
    i = 123;
}
//in the following two functions i gets red
//already your IDE (VS) knows that i should not be changed
//and it forces you not to assign a value to i
//more over you can change the constness of one variable, in different functions
//in the function where i is defined it could be a variable
//in another function it could be constant 
void foo( const int i ) {
    i = 123; 
}
void foo( const int & i ) {
    i = 123; 
}

using "const" where it is needed has the following benefits: * you can change the constness of one variable i, in different functions in the function where i is defined it could be a variable in another function it could be constant value. * already your IDE knows that i should not be changed. and it forces you not to assign a value to i

regards Oops

answered 2010-04-28T07:55:01.850

Your Answer