Can GCC emits a warning/error if a pure function calls a "not pure" function?

248 Views Asked by At

I have discovered the gcc attribute pure and likes to use it, since it seems to me a good way to add additional information in my interface, (alongside the const keyword), and if I have understood its purpose correctly, will allow my compiler to optimize my code with more ease.

But it also seems to me that a pure function should only be able to use functions which are pure themselves. Is there a specific warning that can be enable to check that pure functions only use pure functions (and additionally, that function pointers arguments given to pure functions are also pure functions) ? The second point could be more tricky, I presume.

Using -Wall -Wextra -pedantic-errors, I have not been able to raise any warning.

Maybe I'm doing this wrong, but I always prefers to have my tools enforce the discipline I've decided to apply, rather than solely counting on the fact that I will not have forgotten it tomorrow morning.

Edit

Can a compiler automatically detect pure functions without the type information about purity? is related, but it seems to me that my problem is much simpler (though I might be wrong) : it is not about detecting whether a function is pure without that information provided by the developper, but check that the functions it internally calls are marked the same way. In others word, check for consistency in "pureness" through the (theorical) call stack, by applying some kind of type checking on the called functions.

1

There are 1 best solutions below

0
On

Per the GCC documentation (emphasis mine):

6.31 Declaring Attributes of Functions

In GNU C, you can use function attributes to declare certain things about functions called in your program which help the compiler optimize calls...

If you declare that a function is pure, you are informing the compiler that it can make certain assumptions about that function.

As stated in the comments: "If the compiler could figure it out, why would you need to use the attribute at all?"