以下代码将y输出为大整数,而不是15
.我不明白为什么.我知道--
和++
操作员在*
操作员面前,所以它应该工作.
下面的代码试图说什么.
/*
Create a variable, set to 15.
Create a pointer to that variable.
Increment the pointer, into undefined memory space.
Decrement the pointer back where it was,
then return the value of what is there,
and save it into the variable y.
Print y.
*/
int main()
{
int x = 15;
int *test = &x;
test++;
int y = *test--;
printf("%d\n", y);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
相反,我将代码更改为以下内容:
int main()
{
int x = 15;
int *test = &x;
test++;
test--;
printf("%d\n", *test);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
该代码输出15
.为什么?
不同之处在于指针之间x++
和++x
之后和之后的增量.
++
是后x
,旧的价值先于增量使用++
在之前x
,则在增量之后使用新值.这将有效:
int y = *(--test);
Run Code Online (Sandbox Code Playgroud)
虽然括号不是必需的,但为了清楚起见,最好使用括号.