c - post increment和post decrement运算符在c语言运算符优先级规则中有什么位置

标签 c operators operator-precedence

根据本 link 中的信息, post increment 和 decrement operators 放在第一位。还有这个link说“以这个例子为例:

foo = *p++;

这里 p 作为表达式的副作用递增,但 foo 取 *(p++) 的值而不是 (*p)++,因为一元运算符将右绑定(bind)到左 "。

但在执行这些链接后,几乎没有任何反应。

#include<stdio.h>
#include<stdlib.h>
int main()
{
    int i = 1;
    int *iptr;
    iptr = &i;
    int num = *iptr++;//1) In this expression the value of 'i' is assigned to num. And an attempt of post incrementing the address stored in *iptr is done as side effect.
    printf("Num value: %d\n",num);

    printf("Pointer: %d\n",*iptr);//2) The address of *iptr is not incremented. If it was then the value of 'i' would not be printed instead it would print the incremented address itself.

    printf("Post increment: %d\n",*iptr++);//3) The address of *iptr will be post incremented (which didn't happen in case of num). But for now the value of 'i' will be printed.

    printf("After increment: %d\n",*iptr);//4) Now the incremented address stored in *iptr will be displayed as there is no value assigned to that address.
    return 0;
}

在上面的实验中,只有在语句终止符之后才能看到post increment 的效果。但是,如果对赋值运算符的右操作数进行后递增,即使在语句终止符之后也看不到任何效果。 E.G int num = *iptr++; (如上述实验中所述)。那么后自增和自减运算符在运算符优先级规则中究竟处于什么位置。

最佳答案

您的代码的问题在于它具有未定义的行为:当您将指针指向单个局部变量时,取消引用递增的指针会产生未定义的行为。

取消引用递增指针对于指向数组的指针是明确定义的。

int array[] = {1, 2, 3};
int *iptr = &array[0];
int num = *iptr++;

此外,使用 %d 和取消引用运算符打印 iptr 是不正确的:您需要使用 %p 打印它,在转换 iptrvoid*,不取消引用:

printf("Pointer: %p\n", (void*)iptr);
// No asterisk here -----------^

现在一切正常(demo)。

关于c - post increment和post decrement运算符在c语言运算符优先级规则中有什么位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43882066/

相关文章:

php - PHP 中的引用赋值运算符 =&

c - 为什么windows API需要传入那么多参数?

Python C 扩展 - 为什么可调用 C 函数必须接受参数并返回 PyObject *

C 程序的 Case Switch 无法正确运行

c++ - C中的&&运算符是什么

c++ - C++中赋值语句的求值顺序

c - C 中的求和无法解决

php - 用PHP中的@运算符抑制错误

parsing - 在Menhir/Ocamlyacc中为运算符(operator)指定动态优先级和优先级

c++ - 为什么后缀运算符++的优先级高于前缀运算符++?