What is recommended to use, passing a structure as a pointer to const i.e.
int doCalculations(const MyStruct* my_struct);
or passing the struct by value, as in,
int doCalculations(MyStruct my_struct);
and why?
In C++ I recall reading somewhere that passing references to const should be used when the struct/Class has a non-trivial constructor. In C although there are no constructors, I imagine it would still take some time to make a local copy of the struct.
If you intend to modify your struct then you obviously have to pass it by pointer.
If you do not intend to modify your struct then it is still general practice to pass by pointer to avoid unnecessary copying. A pointer will take up sizeof(void *) memory, but may be passed by register (thus not using stack memory at all).
Passing a struct by value will almost always make a copy of it on the stack.
Two scenarios where you have to choose:
volatile) fields then you will probably want to pass it by pointer in order to always have the most up to date version.frees that memory) then you will obviously have to make a copy of it (pass by value).If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With