那是关于堆栈的吗?我认为最后一个 *p++
是未定义的。 *p++
是指 *(p++)
还是 *p;p++;
?
void test123()
{
char s[] = "123", * p;
p = s;
// 1 2 3
cout << *p++ << endl;
cout << *p++ << endl;
cout << *p++ << endl;
}
void test321()
{
char s[] = "123", * p;
p = s;
//321
cout << *p++ << *p++ << *p++ << endl;
}
int main(void)
{
cout << "123:" << endl;
test123();
cout << "123:" << endl;
test321();
cout << "hello world" << endl;
return 0;
}
我认为结果是未定义的。
最佳答案
*p++
根据运算符优先级计算为 *(p++)
。 p++
所做的是将 p
递增 1 并返回递增前的值。
来自 https://en.cppreference.com/w/cpp/language/operator_incdec
Post-increment and post-decrement creates a copy of the object, increments or decrements the value of the object and returns the copy from before the increment or decrement.
即使在您提到的最后一行,p++
也会返回位置 s+2
,因此取消引用它我们得到 3
,而不是下一个地址
除了评估的顺序(在test321
),这段代码没有未定义的行为。
% 如果表达式是 *++p
它会完全按照你说的去做(但是它仍然不是未定义的,因为每个字符串文字都以零结尾(\0
).
关于c++ - 为什么是这个结果?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56338830/