This is the mail archive of the gcc@gcc.gnu.org mailing list for the GCC project.


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]
Other format: [Raw text]

Re: Possible missed optimization opportunity with const?


On 17/08/16 02:21, Toshi Morita wrote:
I was involved in a discussion over the semantics of "const" in C, and the following code was posted:

#include <stdio.h>
int foo = 0;
const int *pfoo = &foo;
void bar (void)
{
     foo +=3D;

I assume that's a typo?

}
int main(void)
{
    int a, b;
    a = *pfoo;
      bar();
      b = *pfoo;
    printf("a: %d, b: %d\n", a, b);
}


This code when compiled with gcc 4.8.2 using the optimization option -O3 produces:

a: 0, b: 1


So it appears even though pfoo is a const int *, the value *pfoo is read twice.

Would it be valid for the code to print a:0, b: 0?
If so, is this a missed optimization opportunity?


No, it would not be valid. Declaring pfoo as a "const int*" tells the compiler "I will not change anything via this pointer - and you can optimise based on that promise". It does /not/ tell the compiler "the thing that this points to will not change".

So the compiler is correct in reading *pfoo twice.


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]