Passing a large const construct to a function

Let's say I compile the following with GCC 5.4 s -O2

or -O3

optimization layer.

typedef struct {
  int data[90];
} huge_t;

int foo( const huge_t bar );

// ...

huge_t x = { 0 };
foo(x);

      

Here I would venture to say that you don't need to create a second copy x

on the stack, because you foo

don't (should) modify your argument. (When) will GCC come to the same conclusion?

In other words, is it okay for me to work with const

type arguments huge_t

for convenience or use pointers? I could imagine that both versions are "good style" in one sense or another and value informed opinion a lot.

+3


source to share


1 answer


If you are looking here: Why doesn't struct pass by reference, general optimization?

It is highly unlikely that any C compiler will make this optimization. This is generally unsafe.



Never assume that your optimizer will do what you want it to do. Optimizers have to follow certain rules so they never break your code. Sometimes you know that something is safe when the optimizer cannot. If for performance you need your code to behave in a certain way, write it that way.

+5


source







All Articles