In your example the compiler is not given the guarantee that
the object 'foo' in question can only be modified through the pointer.

We can make such guarantee by adding the `restrict` qualifier
to the pointer, like this:

    const int *restrict pfoo = &foo;

With -O3 on GCC 6.1 the modified code produces:

    a: 1, b: 1

However as long as there is a restrict pointer pointing to an object,
modifying it _not_ through that pointer results in undefined behavior.

------------------                               
Best regards,
lh_mouse
2016-08-17

-------------------------------------------------------------
发件人:Toshi Morita <tm314...@yahoo.com>
发送日期:2016-08-17 08:21
收件人:gcc@gcc.gnu.org
抄送:
主题:Possible missed optimization opportunity with const?

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;
}
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?

Toshi 


Reply via email to