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. Aconstexprfunction must have literal return and parameter types and the body can only contain static asserts, typedefs, using declarations and directives and one return statement. Aconstexprfunction may be called in a constant expression.Having looked at the meaning of
__atribute__((const)), the answer is no, you cannot do this with standard C++. Usingconstexprwill 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).