use*_*893 10 c struct increment pre-increment
假设我有一个如下定义的结构
struct my_struct
{
int num;
};
Run Code Online (Sandbox Code Playgroud)
....
这里我有一个指针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;
}
Run Code Online (Sandbox Code Playgroud)
这三种递增方式是否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);
}
Run Code Online (Sandbox Code Playgroud)
输出:
foo(my_struct*): # @foo(my_struct*)
incl (%rdi)
ret
bar(my_struct*): # @bar(my_struct*)
incl (%rdi)
ret
Run Code Online (Sandbox Code Playgroud)
如你所见,没有任何区别.
前两个之间唯一可能的区别是当你在表达式中使用它们时:
my_ptr->num = 0;
int x = my_ptr->num++; // x = 0
my_ptr->num = 0;
int y = ++my_ptr->num; // y = 1
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
12089 次 |
| 最近记录: |