Consider this code:
struct s { /* ... */ };
void f(struct s x) { /* ... */) /* (1) */
/* or */
void f(const struct s *x) { /* ... */ } /* (2) */
When struct s
has a decent size, in which case should we prefer the first form?
Are you asking which is better?
It depends what you are trying to do - the second form with a pointer will be more efficient. But if you just want to pass a value to f
and not have to worry about side-effects then you might go with the first signature - as long as the struct
is not too large.
I would suggest reading this.
When struct s
is of decent size as you say, then you should avoid passing it by value, especially in recursive functions.
Passing a struct by value means that it gets copied before the function invocation. That results in slower execution and greater memory utilization. Also note that the struct
is going to be allocating in the stack and in some systems the stack size is pretty limited.
I would suggest using a pointer in every case unless you need multiple copies of a structure to be modified by functions and you don't want those modifications only visible within each function's scope.
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