This is the mail archive of the gcc@gcc.gnu.org mailing list for the GCC project.


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]

Re: gcc behavior re const optimization



> I was just interested to know if gcc could take advantage of const
> correctness to optimize generated code, which kind of optimizations
> gcc would be likely to perform, and what programming practices are
> likely to help the optimizer spot these optimizations.

gcc (or any compiler) is limited in its ability to do this because it is
legal in C and in C++ to cast away const and modify an object, provided
that the original object is non-const.  This means that gcc cannot assume
that, for instance, in

int func(const int* arg);

void some_function() {

	int foo = 2;
	int bar = func(&foo);
	int fred = foo;
	...
}

that fred gets 2, because func is allowed to cheat.

Now, the compiler is free to generate code that dumps core for

const int foo = 2;

...
	int bar = func(&foo);
...

if func attempts to modify foo IN THIS CASE, because the actual object is
const.  The result of all this is that the const modifier for a pointer
or reference is only a sort of hint, something like "we can't promise
that you are allowed to modify the object this thingie refers to".

The real reason for const correctness is code maintainability.


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]