Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why doesn't GCC force parameters in __attribute__((pure)) functions to be const?

Tags:

c++

attributes

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.

like image 880
emchristiansen Avatar asked Jan 20 '23 15:01

emchristiansen


1 Answers

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.

like image 112
molbdnilo Avatar answered Feb 19 '23 09:02

molbdnilo