This is the mail archive of the
mailing list for the GCC project.
Re: Possible missed optimization opportunity with const?
- From: David Brown <david dot brown at hesbynett dot no>
- To: Toshi Morita <tm314159 at yahoo dot com>, "gcc at gcc dot gnu dot org" <gcc at gcc dot gnu dot org>
- Date: Thu, 18 Aug 2016 15:04:19 +0200
- Subject: Re: Possible missed optimization opportunity with const?
- Authentication-results: sourceware.org; auth=none
- References: <1637972460.15325965.1471393300211.JavaMail.email@example.com> <1637972460.15325965.1471393300211.JavaMail.firstname.lastname@example.org> <57B47168.email@example.com> <1646493700.16522102.1471473899633.JavaMail.firstname.lastname@example.org>
On 18/08/16 00:44, Toshi Morita wrote:
> David Brown <email@example.com> wrote:
>> 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.
> The revised example posted by Kei uses "const int const *pfoo" and GCC
> is able to remove the second read, so this interpretation of const seems
I didn't see the post you are referring to - was it sent to the mailing
list, or only your email address?
But if I can make a guess here, the difference here is that now the
pointer object "pfoo" itself is const, and therefore cannot be modified
(without causing undefined behaviour). So the compiler knows that it
will definitely point to "foo", and can use that information to optimise
When "pfoo" was not "const", the compiler does not know that pfoo points
to foo in main - it could point somewhere else. (In particular, a
file-scope constructor in another module might change it, since pfoo has
external linkage.) Thus it does not know if bar() changes *pfoo, and it
has to read *pfoo twice. You would get the same effect by making pfoo
"static", since the compiler then knows that it's value is &foo at the
start of main().