假设我有一个定义如下的结构
struct my_struct
{
int num;
};
....
这里我有一个指向 my_struct
的指针,我想对 num
做一个增量
void foo(struct my_struct* my_ptr)
{
// increment num
// method #1
my_ptr->num++;
// method #2
++(my_ptr->num);
// method #3
my_ptr->++num;
}
这 3 种递增 num
的方法是否做同样的事情?
说到这里,预增量真的比后增量更有效吗?
谢谢!
最佳答案
前两个会产生相同的效果(当它们单独成一行时),但第三个方法不是有效的 C 代码(你不能把 ++
放在那里) .
至于效率,没有区别。您可能听说过人们谈论的不同之处在于,在 C++ 中,您递增非指针数据类型,例如迭代器。在某些情况下,那里的预增量可能会更快。
您可以使用 GCC Explorer 查看生成的代码.
void foo(struct my_struct* my_ptr)
{
my_ptr->num++;
}
void bar(struct my_struct* my_ptr)
{
++(my_ptr->num);
}
输出:
foo(my_struct*): # @foo(my_struct*)
incl (%rdi)
ret
bar(my_struct*): # @bar(my_struct*)
incl (%rdi)
ret
如您所见,没有任何区别。
前两者之间唯一可能的区别是当您在表达式中使用它们时:
my_ptr->num = 0;
int x = my_ptr->num++; // x = 0
my_ptr->num = 0;
int y = ++my_ptr->num; // y = 1
关于c - 增加结构成员,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12663203/