-1

I think I haven't grasped the proper idea behind returning something that is const.

If I'm having a function which returns const value, doesn't it means that I cannot change the value after I returned it?

Why the compiler allows me to cast my const to a non-const variable?

Or it works only with const pointers?

const int foo(int index) {
    return ++index;
}

int main(){
    int i = foo(1); // why can I do this?
    ++i;

    return 0;
}
Dannz
  • 495
  • 8
  • 20
  • A `const int` can be copied pretty easily, which is what happens when you assign it to `i`. A `const` pointer is different because what you're pointing *at* is `const` unless you have `const X* const` in which case both the pointer and the target are `const`. See [examples like this](http://stackoverflow.com/questions/1143262/what-is-the-difference-between-const-int-const-int-const-and-int-const) for more explanation. Returning a `const int` is pretty pointless in any case since they're so cheap to copy. – tadman Feb 15 '17 at 07:26
  • 2
    See http://stackoverflow.com/questions/6299967/what-are-the-use-cases-for-having-a-function-return-by-const-value-for-non-built and http://stackoverflow.com/questions/8716330/purpose-of-returning-by-const-value for more information – wkl Feb 15 '17 at 07:28
  • So returning const by value is useless? @tadman – Dannz Feb 15 '17 at 07:28
  • 1
    Yeah, it's pretty much irrelevant if you're going to copy it anyway. It's more common to return a `const` reference where that doesn't necessarily need to be copied. – tadman Feb 15 '17 at 07:29
  • It's a duplicate, il vote to delete the current post. Thank you. – Dannz Feb 15 '17 at 07:29

1 Answers1

4

You're doing the equivalent of this:

const int a = 42; // a cannot be modified
int b = a;        // b is a copy of a...
++b;              // and it can be modified

In other words, you are making a copy of a const object, and modifying said copy.


Note that returning a const value has limited, ehm, value. For built-in types it isn't important. For user-defined types, it can prevent modifying a "temporary" object, at the cost of preventing move semantics. Since C++11 it has become advisable to not return const values.

juanchopanza
  • 223,364
  • 34
  • 402
  • 480