Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Function return value defined as a constant

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

like image 793
Imobilis Avatar asked May 11 '15 09:05

Imobilis


People also ask

Can a function return a constant?

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 .

What is a function return value?

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.

What is const return?

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

How does a function return a value to a function?

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.


2 Answers

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.
like image 63
Christoph Avatar answered Sep 22 '22 18:09

Christoph


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

like image 25
Ignited Avatar answered Sep 22 '22 18:09

Ignited