函数返回值定义为常量

Imo*_*lis 16 c const function

我在很多场合看到过用const类型限定符来定义函数:

const int foo (int arg)
Run Code Online (Sandbox Code Playgroud)

这有什么意义?函数的返回值无论如何都无法改变..

Chr*_*oph 13

在C中,它确实无用,编译器可能会发出相应的警告:

$ 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.
Run Code Online (Sandbox Code Playgroud)

  • @Malina:如果添加`-Wextra`,gcc(在这里使用4.9.2)会有效 (3认同)

Ign*_*ted 11

根据C规范(C99,第6.7.3节):

与限定类型关联的属性仅对作为左值的表达式有意义.

函数不是左值,因此const它们的关键字没有意义.编译器将在编译期间忽略它们.

参考:在线C99标准