__attribute__((const)) vs __attribute__((pure)) in GNU C
GNU C中
1 2 3 4 | __attribute__((const)) int f() { /* ... */ return 4; } |
VS
1 2 3 4 | __attribute__((pure)) int f() { /* ... */ return 4; } |
从ARM编译器的文档(基于gcc):
__attribute__((pure)) function attribute
Many functions have no effects except to return a value, and their return value depends only on the parameters and global variables. Functions of this kind can be subject to data flow analysis and might be eliminated.
__attribute__((const)) function attribute
Many functions examine only the arguments passed to them, and have no effects except for the return value. This is a much stricter class than__attribute__((pure)) , because a function is not permitted to read global memory. If a function is known to operate only on its arguments then it can be subject to common sub-expression elimination and loop optimizations.
因此,TL; DR:
GCC手册中解释了这种差异。最值得注意的是
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.
请注意,如果函数传递了指针并检查该指针的上下文,则无法将其声明为
您可以使用结构在C中返回多个值,这样可以更轻松地使用