Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pure functions in C++11

Tags:

c++

gcc

c++11

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.

like image 960
Cartesius00 Avatar asked Dec 02 '12 22:12

Cartesius00


1 Answers

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

like image 160
Joseph Mansfield Avatar answered Oct 21 '22 09:10

Joseph Mansfield