指向struct或struct本身的指针?

md5*_*md5 6 c performance struct pointers

考虑以下代码:

struct s { /* ... */ };

void f(struct s x) { /* ... */) /* (1) */
/* or */
void f(const struct s *x) { /* ... */ } /* (2) */
Run Code Online (Sandbox Code Playgroud)

什么时候struct s有合适的尺寸,在这种情况下我们应该更喜欢第一种形式?

Jus*_*ier 6

你问哪个更好?

这取决于你想要做什么 - 带指针的第二种形式会更有效率.但是如果你只是想传递一个值f而不必担心副作用,那么你可以选择第一个签名 - 只要struct它不是太大.

  • 我也不确定你说的是什么副作用.当然,const可以被抛弃,但是你正在实现这个功能,对吧?所以,嗯......不要这样做或带走const.我更喜欢第二种形式. (2认同)