是否 *p++解除引用后增加?
我不太确定这里的顺序是什么。是吗: 1)增加指针p的值后取消引用它 2) 在增加指针 p 的值之前先取消引用它
I'm not really sure what the order here is. Is it:
1) Dereference the value of pointer p after increasing it
2) Dereference the value of pointer p before increasing it
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
增量和取消引用之间没有顺序。但是,
*
运算符适用于p++
的结果,即递增之前p
的原始值。There is no ordering between the increment and the dereference. However, the
*
operator applies to the result ofp++
, which is the original value ofp
prior to the increment.在运算符表中,您可以看到后缀运算符
++
的位置高于*
一元运算符。因此,
*p++
增加p
(而不是*p
),并返回p
的地址值包含在增量之前(因为它是后缀++
)。但顺序取决于实施。它可以从取消引用 p 开始,然后增加它,并且它可以存储 p 的旧值,增加它,然后取消引用旧值。
In the operators table, you can see that the suffix operator
++
have higher place than the*
unary operator.Hence,
*p++
increasep
(and not*p
), and return the value of the address thatp
contained before the increment (since it's thesuffix ++
).But the order is implementation-depend. It may begin by dereferencing p, and then increase it, and it may store the old value of
p
, increase it, and then dereference the old value.尝试一下。该程序
打印
显示
++
适用于p
,而不是*p
,并且增量发生在取消引用之后。编辑:(感谢 @EricLippert 说服我退出 K & R)
不仅可能存在事后关系,而且根据 K & R,可能存在事后关系。 R第203页,一定有:
(强调我的)
当然,我不相信 K & R 在存在多线程的情况下讲述了有关 C 语义的任何内容(根据 Wikipedia pthreads 规范于 1995 年发布),但对于单线程程序 K & R说的很清楚了
Try it. The program
prints
showing that the
++
applies top
, not to*p
, and that the increment happens after the dereference.EDIT: (Thanks to @EricLippert for convincing me to pull out K & R)
Not only may there be a happens-after relationship, but according to K & R page 203, there must be:
(emphasis mine)
Granted, I don't believe that K & R says anything about the semantics of C in the presence of multithreading (according to Wikipedia the pthreads specification was released in 1995), but for a single-threaded program K & R is pretty clear.
给定
q = *p++;
,q 获取 p 在增量之前指向的值。另一种说法是,表达式*p++
的值是p在递增之前所指向的值。Given
q = *p++;
, q gets the value that p pointed to before the increment. Another way to say it is that the value of the expression*p++
is the value that p pointed to before being incremented.后缀
++
和--
运算符本质上比前缀一元运算符具有更高的优先级。因此,*p++
等价于*(p++)
;它递增p
,并返回p
在递增p
之前所指向的值。要增加
p
指向的值,请使用(*p)++
(或者可能是++*p
,如果计算顺序为副作用并不重要)。The postfix
++
and--
operators essentially have higher precedence than the prefix unary operators. Therefore,*p++
is equivalent to*(p++)
; it incrementsp
, and returns the value whichp
pointed to beforep
was incremented.To increment the value pointed to by
p
, use(*p)++
(or perhaps++*p
, if the evaluation order of the side effect doesn't matter).