post 增量的优先级
Precedence of post increment
任何人都可以解释以下代码的输出是什么以及为什么?
int main()
{
int i[] = {3, 5};
int* p = i;
int j = --*p++;
printf("%d\n%d\n", j,*p);
system("pause");
return 0;
}
我实际上要回答这个问题,尽管 "the OP simply needs to compile the code and run it" 是真的,因为对于初学者来说这 是 之一并不明显给出正确答案的情况。人们总是在这个网站上询问为什么表面上相似的代码(确实有未定义的行为)给出了令人惊讶的答案。
int j = --*p++;
表示
int j = *p - 1;
*p = j;
p += 1;
即*p
(p
指向的值)减1,减后的值写入j
,然后 p
本身递增。
这里没有未定义的行为,因为原始形式中的--
和++
运算符作用于两个不同的数据对象。由于多次使用 side-effect 运算符而具有未定义行为的表达式都涉及在同一表达式中两次修改 相同的数据对象 ("without an intervening sequence point").
(如果您想知道 为什么 --
适用于 *p
但 ++
仅适用于 p
,答案是"because that's what the grammar of the language says. Sorry, this is just one of those things you have to memorize.")
任何人都可以解释以下代码的输出是什么以及为什么?
int main()
{
int i[] = {3, 5};
int* p = i;
int j = --*p++;
printf("%d\n%d\n", j,*p);
system("pause");
return 0;
}
我实际上要回答这个问题,尽管 "the OP simply needs to compile the code and run it" 是真的,因为对于初学者来说这 是 之一并不明显给出正确答案的情况。人们总是在这个网站上询问为什么表面上相似的代码(确实有未定义的行为)给出了令人惊讶的答案。
int j = --*p++;
表示
int j = *p - 1;
*p = j;
p += 1;
即*p
(p
指向的值)减1,减后的值写入j
,然后 p
本身递增。
这里没有未定义的行为,因为原始形式中的--
和++
运算符作用于两个不同的数据对象。由于多次使用 side-effect 运算符而具有未定义行为的表达式都涉及在同一表达式中两次修改 相同的数据对象 ("without an intervening sequence point").
(如果您想知道 为什么 --
适用于 *p
但 ++
仅适用于 p
,答案是"because that's what the grammar of the language says. Sorry, this is just one of those things you have to memorize.")