What is the difference between the expressions "int a" and "const int & a" as function arguments in C ++?

4

Let's say I have two functions:

int soma_a(int a, int b){
    return a + b;
}

and

int soma_b(const int& a, const int& b){
    return a + b;
}

What would be the difference between soma_a and soma_b

    
asked by anonymous 07.08.2018 / 21:55

2 answers

3

The first one is passed by value, that is, the value of the argument being used in the call of this function is copied to the parameter of the function soma_a() .

The second value of the argument is not copied, a reference is used in place, that is, opaque a pointer is created by pointing to the location where the argument value is, and that address is copied to the parameter of the function soma_b() . Since there is const means that the function is forbidden to change this value, it will be read only, so there is a contract guaranteeing to the caller that the value will remain intact.

In int does not make sense because int is usually the same size or even smaller than the size of a pointer, so the copy costs the same thing or more. usually this is most useful in cases where the past structure is larger than a pointer.

In written form both will behave exactly the same, but the former will be more efficient in this specific case.

If it did not have const then it might be useful to make the parameter serve as output as well, so changing its value inside the function would cause a side effect on the argument, after all the argument and parameter are in same address, you passed the address, not a value independently, they are completely connected because it is the same thing. In this case the argument has to be a variable.

#include <iostream>
using namespace std;

int soma_b(int& a, const int& b) {
    a = 4;
    return a + b;
}

int main() {
    int x = 2;
    cout << soma_b(x, 3) << endl;
    cout << x;
}

important readings to better understand the subject and some related, even if in another language:

07.08.2018 / 22:13
1

In C ++, in addition to variables, we can also use numbers or characters whose values do not change. They are called constants. In this case, in soma_b , you reference the variables a and b as being constants, so that their values can not be changed. (even with a command cin >> a >> b >> endl;

    
07.08.2018 / 22:13