简体   繁体   English

Postfix对指针的一元增量操作

[英]Postfix unary increment operation on pointers

I newly started working with C and Pointers . 我刚开始使用CPointers There is a concept that confuses me regarding to unary increment operation on pointers. 关于指针的一元增量操作,有一个使我感到困惑的概念。

int num1, *pnum1
num1 = 2;
pnum1 = &num1;
printf("%d \n before: " , *pnum1);
num1 = (*pnum1)++;
printf("%d \n after: " , *pnum1);
return 0;

Since the unary increment operator (++) has greater precedence than the dereference operator (*), I put *pnum1 inside braces. 由于一元增量运算符 (++)的优先级高于取消引用运算符 (*),因此我将* pnum1放在花括号中。 What I expect was to see below result: 我期望看到以下结果:

after: 3 之后:3

But it doesn't increment the value of num1. 但是它不会增加num1的值。 Why would it be the case? 为什么会这样呢? Wasn't it suppose to increment the value of num1? 是不是应该增加num1的值?

This is undefined behaviour. 这是未定义的行为。 You're incrementing num1 (via (*pnum1)++ ), then assigning the result back to num1 . 您要递增num1 (通过(*pnum1)++ ),然后将结果分配回num1 The order that incrementing and assigning happen is undefined in this case, so it could get the old value of num1 , increment num1 , and then assign the old value back to num1 , which seems to be what your compiler has chosen to do. 在这种情况下,递增和赋值发生的顺序是不确定的,因此它可以获取旧值num1 ,增量num1 ,然后将旧值分配回num1 ,这似乎是编译器选择执行的操作。

If you try num1 = num1++ instead, your compiler will probably warn you about this. 如果改用num1 = num1++ ,则编译器可能会警告您。

The solution is not to do stuff like this, since it's undefined behaviour. 解决方案是不要做这样的事情,因为这是不确定的行为。

Look up "sequence points" for more information. 查找“序列点”以获取更多信息。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM