Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
302 views
in Technique[技术] by (71.8m points)

gcc - __attribute__((const)) vs __attribute__((pure)) in GNU C

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

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

vs

__attribute__((pure)) int f() {
    /* ... */
    return 4;
}
question from:https://stackoverflow.com/questions/29117836/attribute-const-vs-attribute-pure-in-gnu-c

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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:

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.

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.

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.

A const function is always pure.

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

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...