As jonnin said, using const can be useful when returning references or pointers (to specify that the object being referred to should not be modified) but there is no reason to use it for a simple int return type like you're doing here.
GCC with -Wignored-qualifiers (one of the flags enabled by -Wextra) generates a warning when compiling your code:
warning: type qualifiers ignored on function return type [-Wignored-qualifiers]
const int func(void)
^~~~~
|
jonnin wrote: |
---|
Almost all uses of const could be taken out and it would work fine, but putting them in throws an error that protects you from messing up. |
It's true for some uses of
const, but it's definitely not true for all uses.
If you for example have a function that accepts a reference to const...
and then you remove the const
then you would no longer be able to call that function with a const objects.
1 2
|
const T obj;
foo(obj); // worked before but now gives an error.
|
So now you need to go and change the definition of the object so that it also doesn't use const
1 2
|
T obj;
foo(obj); // OK (although it's no longer clear from just looking a the code whether the object will be modified or not)
|
Sometimes the object that you pass to the function is not declared right next to the function call like in the example above. Instead it might be passed as an argument to the function which might come as an argument from yet another function and so on. So removing a single const actually forces you to have to go and remove const in a lot of other places too.
So when dealing with pointers and references (and member functions) you need to be consistent in your usage of const. But in other places (e.g. when declaring a local variable) you can often leave out const without breaking code elsewhere.