GNU C 中的 __attribute__((const)) 与 __attribute__((pure)) [英] __attribute__((const)) vs __attribute__((pure)) in GNU C

查看:23
本文介绍了GNU C 中的 __attribute__((const)) 与 __attribute__((pure))的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

GNU C 中的 __attribute__((const))__attribute__((pure)) 有什么区别?

What is the difference between __attribute__((const)) and __attribute__((pure)) in GNU C?

__attribute__((const)) int f() {
    /* ... */
    return 4;
}

__attribute__((pure)) int f() {
    /* ... */
    return 4;
}

推荐答案

区别在GCC 手册.最值得注意的是 const 函数只能使用传入的参数而不使用任何内存,而 pure 函数也可以在约束下访问内存:

The difference is explained in the GCC manuals. Most notably a const function may only use the arguments passed in and not any memory, whereas a pure function can access memory too, under constraints:

pure 属性禁止函数修改通过检查函数返回值以外的方式可观察到的程序状态.但是,使用 pure 属性声明的函数可以安全地读取任何非易失性对象,并以不影响其返回值或程序可观察状态的方式修改对象的值.

The pure attribute prohibits a function from modifying the state of the program that is observable by means other than inspecting the function’s return value. However, functions declared with the pure attribute can safely read any non-volatile objects, and modify the value of objects in a way that does not affect their return value or the observable state of the program.

__attribute__ ((pure)) 表示该函数没有副作用,返回值取决于参数和全局变量的状态.因此,如果参数相同,并且调用者没有做任何事情来改变调用之间的全局变量的状态,优化器可以安全地忽略对它的一些调用.

The __attribute__ ((pure)) means that the function has no side effects and the value returned depends on the arguments and the state of global variables. Therefore it is safe for the optimizer to elide some calls to it, if the arguments are the same, and the caller did not do anything to change the state of the globals in between the calls.

__attribute__ ((const)) 表示返回值完全是参数的函数,如果任何参数是指针,那么指针不能被取消引用.

The __attribute__ ((const)) means that the return value is solely a function of the arguments, and if any of the arguments are pointers, then the pointers must not be dereferenced.

const 函数总是 pure.

const 函数的示例是 中的 abs 函数和 中的一些数学函数.math.h>:sqrtexp 等(虽然它们可能会受到舍入模式的影响).

Examples of const functions would be the abs functions from <stdlib.h> and some mathematical functions from <math.h>: sqrt, exp, etc. (Though they might be subject to rounding modes).

pure 的示例但非 const 函数将是诸如 strlen 之类的函数 - 因为它取消引用传入的指针.

Examples of pure but non-const functions would be such functions as strlen - as it dereferences the pointer passed in.

这篇关于GNU C 中的 __attribute__((const)) 与 __attribute__((pure))的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆