using only standard C ++ 11:
namespace g{ int x; } constexpr int foo() {
here is another example:
constexpr int foo( int blah = 0 ) { return blah + 42; // OK } int main( int argc, char** ) { int bah[foo(2)]; // Very constant. int const troll = foo( argc ); // Very non-constant. }
The GCC __attribute__( const ) value is documented in the GNU compiler documents as & hellip;
Many functions do not check values ββother than their arguments, and have no effects other than the return value. Basically, this is a slightly more strict class than the pure attribute below, since functions are not allowed to read global memory.
We can assume that the result of the function should depend only on the arguments and that the function should not have side effects.
This allows you to use a more general class of functions than C ++ 11 constexpr , which makes the inline function, limits the arguments and result of the function to literals and limits the "active" body functions of the single return function, where (C ++ 11 Β§7.1.5 / 3)
- each call to the constructor and the implicit conversion used to initialize the return value (6.6.3, 8.5) must be one of the allowed in the constant expression (5.19)
As an example, it is difficult (I think not impossible, but difficult) to make the constexpr sin function.
But the purity of the result matters only for two parties:
When it is known that it is clean, the compiler can overcome challenges with known results.
This is mainly an optimization of macro-generated code. Replace macros with inline functions to avoid stupidly generating identical subexpressions.
When it is known that it is clean, the programmer can completely remove the call.
This is just a matter of proper documentation. :-)
Thus, instead of looking for a way to express purity, for example. sin in the language, I suggest simply avoiding code generation through macros, as well as writing pure functions as such.
And use constexpr for functions where it is practically possible (unfortunately, as of December 2012, the last Visual C ++ compiler does not yet support constexpr ).
There is a previous question about the relationship between pure and constexpr . Basically, every constexpr function is pure, but not vice versa.