> Is it really cheating or trickery to declare a function constant even though it accesses the
larger environment? Or is it just helping the compiler properly classify the function when it
doesn't have enough information to do it itself?
Yes! Well, maybe it's not cheating, but it's definitely lying, and you'd better start
expecting your code to start failing in mysterious ways when you add more stuff to your
program or you switch to a new or different compiler.
Really, if you want to help the compiler, help it directly, don't try to trick the optimizer
into doing what you want. If you're concerned about
if (count(foo)) bar(count(foo));
where count() isn't really constant, but in this one case you know for a fact that it the
result won't change, just write
tmp = count(foo); if (tmp) bar(tmp);
> All programs make assumptions about their environment. For example, that there isn't another
thread running around overwriting the memory in which the program's variables are stored.
There's a difference between valid documented assumptions (that my kernel separates processes
properly) and non-guaranteed observations (hey, if I lie to the compiler here then it seems to
generate better code). In the first case, a problem is clearly a bug in the kernel and so it
would be fixed if it showed up. In the second, it's your own bug when the assumption proves
> So isn't it legitimate to make the environmental assumption that a certain file's contents
don't change while the program runs? With that assumption, a function whose result depends
upon the contents of the file is constant.
Aah, now that's different. If you can look at a function, and the way it behaves in your
program, and guarantee "at any time in my program, during proper usage, this function will
always return the same answer" then sure, call it constant, and you're not cheating or lying
to the compiler, you're just being 100% accurate and using the attribute properly.
My concern with the article it suggests you might declare a function constant, even when it's
not(!), if it helps generate better code. And that's definitely cheating and just asking for