简体   繁体   English

以下两个不同的传递变量方法到函数之间的区别

[英]Difference between the following two different passing variables method into functions

I have the following struct and two kinds of methods listed below. 我有以下结构和下面列出的两种方法。 Which method is better and why? 哪种方法更好,为什么?

typedef struct _MY_ST_
{
  int a;
  int b;
} MY_ST;

Method 1: 方法1:

int func1(MY_ST my_st)
{
  int temp;
  temp = my_st.a + my_st.b;
  return temp;
}

Method 2: 方法2:

int func2(const MY_ST *const my_st)
{
  int temp;
  temp = my_st->a + my_st->b;
  return temp;
}

With such a small structure (2 integers), you won't see a difference. 如此小的结构(2个整数),您将看不到任何区别。

In general, though, it usually makes sense to pass a pointer to the structure, since it avoids unnecessary copying. 通常,尽管如此,将指针传递给该结构通常很有意义,因为它避免了不必要的复制。 But in this specific case, I'd say just go with whatever you're more comfortable with and makes sense for you. 但是在这种特定情况下,我想说的就是随您便,对您来说更有意义。

Also, you don't need the parameter in func2() to be const MY_ST *const my_st . 另外,您不需要func2()的参数为const MY_ST *const my_st const MY_ST *my_str will suffice, because the pointer is passed by copy, so there is no way that the callee will modify the caller's pointer value. const MY_ST *my_str就足够了,因为指针是通过副本传递的,所以被调用方无法修改调用方的指针值。

I would say the second method is better because you only pass a pointer to the memory where your structure is held. 我想说第二种方法更好,因为您只传递了一个指向结构所在的内存的指针。 In the first method you pass the who structure and the computer will duplicate in memory the structure in the function - a copy of the structure will be made. 在第一种方法中,您传递了who结构,计算机将在内存中复制该函数中的结构-将复制该结构。 (but a compiler running optimization may make the two methods equivalent) (但是编译器运行优化可能会使这两种方法等效)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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