__attribute__((const)) is enough
As documented at: https://gcc.gnu.org/onlinedocs/gcc-5.1.0/gcc/Function-Attributes.html , it tells the compiler that the given function does not modify globals (although it can read them).
There is also the pure
subset of const
, which also forbids global reads.
Consider the following simplified example:
int __attribute__((const)) g();
int f(int a) {
int x = a;
g();
return x - a;
}
On g++
4.8 x86_64 -O3
, it compiles to:
xor %eax,%eax
with const
- a large function that does not suppose
a
is not modified without const
There seems to be no finer grained attribute that says that a function does not modify a given variable as you require.
Can __attribute__((const)) be applied to function pointers?
Let's try:
int f(int& a, void __attribute__((const)) (*g)(void)) {
int x = a;
(*g)();
return x - a;
}
Once again, it compiles to xor %eax,%eax
, and to a large function without const
, so the answer is yes.
This syntax was asked at: Function pointer to __attribute__((const)) function?
It also appeared in 2011 on the mailing list at: http://comments.gmane.org/gmane.comp.gcc.help/38052 At the time at least, it only worked for some attributes.
Can __attribute__((const)) be added to the typedef?
This works:
typedef void __attribute__((const)) (*g_t)(void);
int f(int& a, g_t g) {
int x = a;
(*g)();
return x - a;
}
or:
typedef void (g_t)(void);
int f(int& a, g_t __attribute__((const)) g) {
int x = a;
g();
return x - a;
}
But I couldn't find a way to both put the attribute on the typedef and pass a function, not a pointer, like:
typedef void __attribute__((const)) (g_t)(void);
GCC gives a warning saying the attribute was ignored in this case.