在 2020/12/3 下午7:47, Andrea Corallo via Gcc-help 写道: > Hi all, > > I've a piece of code that reduced looks like this: > > #+begin_src C > typedef struct { > void (*fun_ptr)(void); > } x_t; > > x_t *x; > > void > f (void) > { > const x_t const *y = x; > for (int i = 0; i < 1000; ++i) > y->fun_ptr (); > } > #+end_src > > What is the correct way (if any) to express to the compiler that the > value of y->fun_ptr does not get clobbered by the function call itself > so the corresponding load to obtain its value can be moved out of the > loop? How about: ```c void f (void) { int i; for (__auto_type p = ( // warning: use of GCC extension (i = 0), // set `i` to zero y->fun_ptr); // warning: abuse of comma operator i < 1000; ++i) p (); } ``` You would only ever need one `i` in each function, so it'd not be very complicated. The scope of `p` is limited to the enclosing `for` statement. > > My understanding is that the const qualifier is more for diagnostic > reasons and is not sufficient for GCC to make this assumption. OTOH I > cannot give 'fun_ptr' the attribute pure as it's not. > `const` may be used for optimization only if it causes an object to be declared `const`. Something such as `const int x = 42;` is known by the compiler to be immutable, but the result of an indirection through a pointer might not be. -- Best regards, LH_Mouse