If I understand the question correctly, you are asking whether the compiler could optimize
int generate_updated_myt(const my_t c);
such that calls to generate_updated_myt()
would actually pass a pointer instead of of an actual copy of the object (ie., it could act in a similar manner to a C++ const&
).
Consider the following contrived example if access to the local copy of c
were implemented as a reference to the object passed in instead of as an actual copy:
#include <stdio.h>
struct my_t {
int a;
int b[24];
};
int foo(void);
int generate_updated_myt(const struct my_t c)
{
int a = c.a;
foo(); // if c is really a 'pointer' to the passed in object,
// then this call to `foo()` may change the object
// c refers to.
if (a != c.a) {
puts("how did my private copy of `c.a` get changed?");
}
return a;
}
struct my_t g_instance;
int main(void)
{
generate_updated_myt( g_instance);
return 0;
}
int foo(void)
{
int counter = g_instance.a++;
return counter;
}
This is one reason the optimization you suggest is not permitted.
And this doesn't even take into consideration that const
is very easily discarded (even if it might be poor form).