如何在gcc中声明和定义纯函数? [英] How to declare and define a pure function in gcc?
问题描述
那么如何使用const属性声明和定义一个函数呢?
编辑:我对真正的纯函数感兴趣,使用const属性声明的那些,而不是使用pure-attribute声明的。
解决方案示例:
//声明:
int square(int x)__attribute__((const));
//定义:
int __attribute__((const))square(int x)
{
return x * x;
$ p $所有属性的语法几乎相同: __ attribute__((< attribute-name>))
或 __ attribute__((< attribute-name>(< attribute-options>)))
。从您链接到的文档中引用:
$ b
关键字 __ attribute __
允许您指定申报时有特殊的属性。这个关键字后面跟着一个在双圆括号内的属性说明。
有些例子可以链接到其他几个属性,包括纯
:
int square(int )__attribute__((纯粹));
所有你需要的,语法上的,使用 const
,改变纯到 const
:
int square(int)__attribute__((const));
正如评论中指出的那样:如果您使用它在一个定义中,你需要把 __ attribute__((const))
放在不同的位置:
int square(int)__attribute__((const)){...} //不工作
int __attribute__((const))square(int){...} / / does not work
但是 const
和 pure
属性在应用于外部声明时非常有用,所以不应该是一个问题。如果定义可见,GCC通常可以确定该函数是否可以被视为 const
/ 纯粹
帮助。
GCC has the pure and const attributes, where const is actually used for the real pure functions (pure is for idempotent functions which are also side-effect free).
So how do I declare and define a function using the const-attribute?
Edit: I'm interested in the real pure functions, the ones declared with the const-attribute, not the ones declared with the pure-attribute.
解决方案 Example:
// Declaration:
int square (int x) __attribute__ ((const));
// Definition:
int __attribute__ ((const)) square (int x)
{
return x*x;
}
The syntax for all attributes is pretty much the same: __attribute__ (( <attribute-name> ))
, or __attribute__ (( <attribute-name> ( <attribute-options> ) ))
. Quoting from the documentation you link to:
The keyword __attribute__
allows you to specify special attributes when making a declaration. This keyword is followed by an attribute specification inside double parentheses.
There are examples in the documentation you link to for several other attributes, including pure
:
int square (int) __attribute__ ((pure));
so all you need, syntax-wise, to use const
, is change pure
to const
:
int square (int) __attribute__ ((const));
As pointed out in the comments: if you're using it in a definition, then you need to put __attribute__ ((const))
in a different location:
int square (int) __attribute__ ((const)) { ... } // doesn't work
int __attribute__ ((const)) square (int) { ... } // does work
but the const
and pure
attributes are pretty much only useful if they are applied to external declarations, so that shouldn't be a problem. If the definition is visible, GCC is usually able to determine whether the function can be treated as const
/pure
without your help.
这篇关于如何在gcc中声明和定义纯函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!