London guy
London guy

Reputation: 28022

What is the importance of adding the const qualifier in the return for the function below?

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

Upvotes: 1

Views: 186

Answers (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.

Upvotes: 1

Related Questions