I've seen in several occasions functions to be defined with the const
type qualifier just like that:
const int foo (int arg)
What is the point in this? Function's return value cannot be changed anyway..
When the function is executed, it returns the copy of the constant object. Therefore, in cases where we need to alter the object's value later, we should avoid using const .
A return is a value that a function returns to the calling script or function when it completes its task. A return value can be any one of the four variable types: handle, integer, object, or string. The type of value your function returns depends largely on the task it performs.
(C++) const return typeThe value of a return type that is declared const cannot be changed. This is especially useful when giving a reference to a class's internals (see example #0), but can also prevent rarer errors (see example #1). Use const whenever possible [1-7].
A return statement ends the execution of a function, and returns control to the calling function. Execution resumes in the calling function at the point immediately following the call. A return statement can return a value to the calling function.
In C, it is indeed useless, and compilers may emit corresponding warnings:
$ echo 'const int foo (int arg);' | clang -Weverything -fsyntax-only -xc -
<stdin>:1:1: warning: 'const' type qualifier on return type has no effect
[-Wignored-qualifiers]
const int foo (int arg);
^~~~~~
1 warning generated.
According to the C spec (C99, section 6.7.3):
The properties associated with qualified types are meaningful only for expressions that are lvalues.
Functions are not lvalues, so const
keyword for them has no meaning. Compiler will ignore them during compilation.
Reference: Online C99 standard
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With