Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing a const pointer to a struct vs pass by value [duplicate]

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.

like image 908
Grieverheart Avatar asked Dec 07 '25 00:12

Grieverheart


1 Answers

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:

  • If your struct may be modified by an external force (i.e. it has volatile) fields then you will probably want to pass it by pointer in order to always have the most up to date version.
  • If your struct may cease to exist during execution of your function (e.g. another thread frees that memory) then you will obviously have to make a copy of it (pass by value).
like image 161
Sergey L. Avatar answered Dec 08 '25 13:12

Sergey L.



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!