What is the use of "const" functions?

341 Views Asked by At

This code looks weird:

const double square(double x) {

    return x*x;

}

Common sense tells me that const in this context means either

  • the function returns a const double

OR

  • it promises not to change the double that was passed in. But it was passed in by value! I don't understand

OR

  • I know that const member functions promise not to change *this, but this is not even a member function.

Edit

What's the point to return a const double if you can save the result in a non-const variable and edit it??

double var = square(4.5); // no compile error

var = 0.3;
5

There are 5 best solutions below

4
On BEST ANSWER

It is weird. As you say:

the function returns a const double

For a user-defined type, this would prevent you from modifying the return value:

square(2) += 5; // Error

although, as noted in the comments, this isn't allowed for a built-in type like double anyway. Even for user-defined types, while you probably don't want to write code like that, there's no point preventing it either.

For more complicated types, returning a const value can actually be harmful: it inhibits move semantics, since a const object can't be moved from. This could hurt performance.

0
On

It returns a const double type variable.

If you do it like this, most compilers give a warning if you try to assign the returned value to a double type.

0
On

A const function with const before the return value is usually used where the function returns a pointer (or perhaps a reference) to say that it will only return const pointers. This one returns a double and that means it only returns doubles that are const.

0
On

That is not a "const function". It is a function which returns a value that is const. A "const function" only applies to member functions, and then the const goes on the right, after the parameter list.

The utility of this for a simple value type is dubious. However, if you were returning a reference to const or a const pointer, or something else, then it could have merit.

The only thing that returning a const of a simple type by value does is make sure that it can't be captured by non-const r-value reference in C++11. Otherwise, they'll just copy the value and be on their way.

5
On

In the example you give, and for any POD type, it makes little sense, but for more complex types it can make sense:-

const SomeClass &SomeFunction ();

which returns a reference to a const object.