Hi Jakub, On 2026-01-29T19:17:31+0100, Jakub Jelinek wrote: > On Thu, Jan 29, 2026 at 07:03:54PM +0100, Alejandro Colomar via Gcc wrote: > > I'm trying to understand why those two attributes exist. > > > > const [...] > > pure [...] > > > > The difference seems to be only that pure functions can read memory > > through pointers. However, that is already obvious information from the > > No, it can read anything in memory. That includes what pointer arguments > point to, but a lot more, anything reachable from the global state at the > point of the call, directly or indirectly.
Hmm. Let's see if I'm misreading the documentation:
However, functions declared with the pure attribute can safely
read any non-volatile objects, and modify the value of objects
in a way that does not affect their return value or the
observable state of the program.
From that sentence, 'in a way...' affects only 'modify...' or also
'read...'? I had always assumed that it affects both. That is, that
a pure function can read the program state, as long as it doesn't affect
the return value of the function (or the observable state).
> int v;
> int *p;
> [[gnu::const]] int foo (int);
> [[gnu::pure]] int bar (int);
> int
> baz (int)
> {
> int a = foo (42) + foo (42);
> int b = 1;
> int c = 1;
> v++;
> p = &b;
> a += foo (42);
> b++;
> a += foo (42);
> a += bar (42) + bar (42);
> v++;
> a += bar (42);
> b++;
> a += bar (42);
> c++;
> a += bar (42);
> return a;
> }
> foo is const, so it can't read memory, so one can call foo just once and
> multiply its result by 4.
> While v++; (change to a global variable) or b++ (change to an automatic
> variable that escaped) can change return value of bar,
This would imply that my understanding of the sentence above is
incorrect.
But then I think it would also invalidate another sentence in the
documentation:
Declaring such functions with the pure attribute allows GCC to
avoid emitting some calls in repeated invocations of the
function with the same argument values.
I had always understood this as implying my understanding of the other
sentence. If that's not true, maybe the documentation should be
revised to clarify.
Could you please confirm what is the correct interpretation of those
sentences, and tweak them to be more explicit?
> while c++; can't
> (it has not escaped). So, one can do
> a += bar (42) * 2;
> v++;
> a += bar (42);
> a += bar (42) * 2;
> c++;
> return a;
> but can't call bar fewer times than 3.
Thanks!
> Jakub
Have a lovely night!
Alex
--
<https://www.alejandro-colomar.es>
signature.asc
Description: PGP signature
