Originally posted by harsman:
Velco, I don’t think you understood Herb Sutter’s point. Usually, you compile one source file at a time and therefore the compiler has no knowledge of if a value that is const in the current translation unit is non-const somewhere else.
Indeed. Howver global optimization means across function calls as opposed to one function at a time. And I have worked with at least two compilers, which can optimize the whole program, before linking. (of course, they re-generated the code from intermediate representation files, AFAICT).
Therefore the const won’t help much. And if the compiler does global optimzation, then it has aliasing information anyway so the const won’t make much of a difference either.
It ain’t so. One needs both pieces of information. A trivial example:
void foo(const float *);
a = b * c[i];
d = e * c[i];
Assuming, c is no aliased, the compiler can save assume that the value of c[i] is the same before and after the call, thus avoiding a second load by possibly using the register where it loaded c[i] the first time (will, “i” does not change too.
One can imagine the same for several elements of c, i.e., for a whole vector.
Also, the “non-changing” property may propagate further on. Some of the expressions (e.g. c[i]) may appear to be loop invariants, thus moved to the prologue. If the compiler can infer “b == e” the above expression become common subexpression and can be eliminated by doing “d = a”. Moreover, this assignment may be moved before the call, if this would result in better instruction scheduling. Etc., etc.
My point is, while “const” by itself is not of much use for an optimizer, it does not stand alone. Coupled with aliasing information is can be useful for almost all optimization phases, by enabling the optimizer to obtain more accurate solutions to the data-flow equations.
That doesn’t mean const isn’t a good thing, being const correct is good. And if you declare a variable const from the start, then it probably enables optimization oppourtunities since the compiler can be certain it’s read only (barring const_cast<> of course).
See, I understand what he said. All of it is true, under some assumptions. I claim that [i]the assumptions/[i] are false.
As for his point, indeed, I do not understand his point. Under some cirmustances “const” won’t give any advantage to the optmization phases? So, what? We wan’t use “const” for this reason? I don’t think so. Then what’s the purpose of the article, other than to make him feel good