Reputation: 1545
Our coding style is we pass a pointer to a struct to a function, when we are modifying the contents of the structure.
However, when we are not modifying the contents of a struct, is there still any reason to prefer passing a pointer to a struct to a function?
Upvotes: 5
Views: 1662
Reputation: 726489
The advantage is in the size being passed: when you pass a large struct
, the compiler generates code to make a copy of that struct
if you pass it by value. This wastes CPU cycles, and may create a situation when your program runs out of stack space, especially on hardware with scarce resources, such as embedded microcontrollers.
When you pass a struct
by pointer, and you know that the function must not make modifications to it, declare the pointer const
to enforce this rule:
void take_struct(const struct arg_struct *data) {
data->field = 123; // Triggers an error
}
Upvotes: 7
Reputation: 12609
Yes, the pointer's size is usually much smaller than the entire struct's size. You save stack and time.
Upvotes: 4