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: Wed, 17 Aug 2016 16:15:04 +0200
- Subject: Re: Possible missed optimization opportunity with const?
- Authentication-results: sourceware.org; auth=none
- References: <1637972460.15325965.1471393300211.JavaMail.firstname.lastname@example.org> <1637972460.15325965.1471393300211.JavaMail.email@example.com>
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:
int foo = 0;
const int *pfoo = &foo;
void bar (void)
I assume that's a typo?
int a, b;
a = *pfoo;
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.