Reputation: 42637
Is it possible to specify compile time "purity" checks in C++?
I.e.:
this function does not read from anything other than it's arguments
this function does not write to anything; it only returns the return value
Upvotes: 4
Views: 576
Reputation: 76541
While there is no portable way to do this, gcc implements function attributes which may be close to what you are interested in. Two specific attributes that you should check out are:
pure - Many functions have no effects except the return value and their return value depends only on the parameters and/or global variables. Such a function can be subject to common subexpression elimination and loop optimization just as an arithmetic operator would be. These functions should be declared with the attribute pure.
and:
const - Many functions do not examine any values except their arguments, and have no effects except the return value. Basically this is just slightly more strict class than the pure attribute below, since function is not allowed to read global memory.
You specify an attribute as part of the prototype:
int square (int x) __attribute__ ((const));
int square (int x)
{
return x * x;
}
Upvotes: 2
Reputation: 2271
const-correctness and high compiler warning levels should do a lot of what you are asking for. Also specifying a very strict modern dialect of C++ for the compiler ( which can annoy the hell out of you, when you are using third-party libraries and code that dont comply )
If not, then there are a plethora of static analysis tools out there, some open source, some expensive like Coverity, Parasoft C++Test and so on.
Upvotes: 4