1

I have the following codebase

#include <cstdio>

int foo(const int &y) {
    static int z = y;
    z = z + 1;
    return z;
}


int main(int argv, char *args[]) {
    int x = 6;
    int r = foo(x);
    printf("The value returned is %d\n", r);
    printf("The vlaue of x is %d\n", x);
    r = foo(x);
    printf("The value returned is %d\n", r);
    printf("The vlaue of x is %d\n", x);

}

Now, the above code prints the same output

The value returned is 7
The value of x is 6
The value returned is 8
The value of x is 6

no matter whether the function is defined like below:

int foo(const int &y) {

or like this:

const int & foo(const int &y) {

So my question is what is the side effect or why is it important to use/not-use the const int & return type instead of int returntype

London guy
  • 27,522
  • 44
  • 121
  • 179
  • 1
    Consider, that a reference may have side effects. If it refers to a variable which could be altered "out of scope" e.g. in a called function which is not obvious. This is true for const references as well (and may be in this case less expected). A local variable may not be changed "secretly" (if not passed to other functions by reference or pointer). – Scheff's Cat Jul 19 '17 at 14:40
  • 1
    I don't think this is an exact duplicate. In the linked question, the OP is using an object type as return type. In this case, an `int` is used and some other things must be considered. – Jérémi Panneton Jul 19 '17 at 14:46

1 Answers1

1

In the case of an int, copy is inexpensive and this is the most preferred way:

int foo(const int &y)

When using a const int& for such a small data type, the indirection will make the code less cache-friendly and probably less efficient than the copy version.