C中是否有const函数?

use*_*540 2 c const function

我的意思是我们可以将C中的函数声明为const

void fun(int iVar) const;

int g_var = 1;

void fun(int iVar)
{
  //do some thing
  g_var = iVar;
}
Run Code Online (Sandbox Code Playgroud)

unw*_*ind 14

不在标准C中,因为没有类或对象(如"类实例,即具有相关函数的数据集合"),该函数没有任何const"反对".

从理论上讲,这种符号可能意味着"这个函数没有全局可见的副作用,它是输入参数的纯函数"但是没有.

作为扩展,GNU GCC编译器支持将函数声明为:const或者pure:

int square(int) __attribute__((pure));
Run Code Online (Sandbox Code Playgroud)

__attribute((pure))部分是GCC特定的.

  • @hyde:C 中的“对象”是“执行环境中的数据存储区域,其内容可以表示值”(C11 3.15.1)。它们与 OOP 对象不同,我怀疑 KingsIndian 提出了 OOP 在这个术语上没有垄断的观点。 (3认同)
  • `因为没有类或对象` 这取决于您所说的对象是什么意思。C 确实有*对象*。 (2认同)
  • 请注意,OP中的函数无论如何都不是纯粹的. (2认同)