英文:
What is the difference between prefix/postfix and increment operator
问题
#include<stdio.h>
void h(int *p) { *p++; }
int main()
{
int index = 100;
h(&index);
printf("%d\n", index);
}
这段代码的输出结果是100,但下面的代码输出结果是101。i+=1 和 i++ 不是同一回事吗?
#include<stdio.h>
void h(int *p) { *p+=1; }
int main()
{
int index = 100;
h(&index);
printf("%d\n", index);
}
英文:
#include<stdio.h>
void h (int *p) { *p++; }
int main ( )
{
int index = 100;
h(&index);
printf("%d\n",index);
}
This code gives 100 but the one below gives 101 as output. Are not i+=1 and i++ same thing?
#include<stdio.h>
void h (int *p) { *p+=1; }
int main ( )
{
int index = 100;
h(&index);
printf("%d\n",index);
}
答案1
得分: 2
这完全是运算符优先级的问题。完整列表在这里。
++的优先级高于*(解引用),但*的优先级高于+=。
因此:
*p++实际上是*(p++),
而*p+=1是(*p)+=1。
在第一种情况下,*p++,增量是在指针p上执行的,并且不会影响它所指向的int。(此外,指针p是一个局部参数,因此对它的更改对调用程序没有影响。)
在第二种情况下,*p+=1,增量是在*p上执行的,因此p指向的int会发生变化。
英文:
It's all a matter of operator precedence. The complete list is here.
++ has precendence over * (dereferencing), but * has precedence over +=.
Therefore:
*p++ is actually *(p++),
whereas *p+=1 is (*p)+=1.
In the first case, *p++, the increment is performed on the pointer p and has no effect on the int it points to. (Also, the pointer p is a local parameter, so changes to it have no effect in the calling routine.)
In the second case, *p+=1, the increment is performed on *p, so the int that p points to is changed.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论