Imobilis
Imobilis

Reputation: 1489

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

Upvotes: 16

Views: 1650

Answers (2)

Ignited
Ignited

Reputation: 781

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

Upvotes: 12

Christoph
Christoph

Reputation: 169603

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.

Upvotes: 13

Related Questions