前缀/后缀和递增运算符之间的区别是什么?

huangapple go评论77阅读模式
英文:

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+=1i++ 不是同一回事吗?

#include<stdio.h>
void h(int *p) { *p+=1; }
int main()
{
    int index = 100;
    h(&index);
    printf("%d\n", index);
}
英文:
#include&lt;stdio.h&gt;
void h (int *p) { *p++; }
int main ( )
{
    int index = 100;
    h(&amp;index);
    printf(&quot;%d\n&quot;,index);
}

This code gives 100 but the one below gives 101 as output. Are not i+=1 and i++ same thing?

#include&lt;stdio.h&gt;
void h (int *p) { *p+=1; }
int main ( )
{
    int index = 100;
    h(&amp;index);
    printf(&quot;%d\n&quot;,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.

huangapple
  • 本文由 发表于 2023年6月19日 23:34:47
  • 转载请务必保留本文链接:https://go.coder-hub.com/76508119.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定