简体   繁体   中英

Pointer to struct or struct itself?

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.

当你想要f获得x的副本而不是指向xconst指针时,首选第一个表单。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM