5

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?

octopusgrabbus
  • 10,555
  • 15
  • 68
  • 131
Deepak
  • 1,503
  • 3
  • 22
  • 45

2 Answers2

7

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
}
Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
4

Yes, the pointer's size is usually much smaller than the entire struct's size. You save stack and time.

SzG
  • 12,333
  • 4
  • 28
  • 41