The following code compiles without warnings under GCC 4.2, and as far as I can tell, it really shouldn't:
#include <fstream>
__attribute__((pure))
double UnpureFunction(double* x) {
x[0] = 42;
return 43;
}
int main () {
double x[] = {0};
double y = UnpureFunction(x);
printf("%.2f %.2f\n", x[0], y);
}
(It prints "42.00 43.00".)
As I understand it, the pure attribute tells the compiler that the function has no external effects (see the section on "pure" here). But UnpureFunction is modifying its parameter. Why is this allowed to happen? At the very minimum, the compiler could automatically make every parameter const.
As far as I know, pure
is your promise to the compiler, but it won't try and verify that you're not lying.
Even if it did force parameters to be const
, those parameters could be lying (e.g. an object might have a mutable member that's modified when your code calls a member function).
If you're looking for const correctness, use const
parameters. The pure
and const
attributes are there to provide hints that can be used for optimization.
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