Can one in C++11 somehow in gcc
mark a function (not a class method) as const
telling that it is pure and does not use the global memory but only its arguments?
I've tried gcc
's __attribute__((const))
and it is precisely what I want. But it does not produce any compile time error when the global memory is touched in the function.
Edit 1
Please be careful. I mean pure functions. Not constant functions. GCC's attribute is a little bit confusing. Pure functions only use their arguments.
Are you looking for constexpr
? This tells the compiler that the function may be evaluated at compile time. A constexpr
function must have literal return and parameter types and the body can only contain static asserts, typedefs, using declarations and directives and one return statement. A constexpr
function may be called in a constant expression.
constexpr int add(int a, int b) { return a + b; }
int x[add(3, 6)];
Having looked at the meaning of __atribute__((const))
, the answer is no, you cannot do this with standard C++. Using constexpr
will achieve the same effect, but only on a much more limited set of functions. There is nothing stopping a compiler from making these optimizations on its own, however, as long as the compiled program behaves the same way (the as-if rule).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With