后递增和后递减运算符在 C 语言的运算符优先级规则中占什么位置



根据此链接中的信息,后递增和递减运算符排在第一位。这个链接说" 举个例子:

foo = *p++;

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

但是在这样做之后,几乎没有发生任何作为这些链接中提到的信息。

#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: %dn",num);
    printf("Pointer: %dn",*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: %dn",*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: %dn",*iptr);//4) Now the incremented address stored in *iptr will be displayed as there is no value assigned to that address.
    return 0;
}

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

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

取消引用递增指针是为数组中的指针明确定义的。

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

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

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

现在一切都按预期工作(演示(。

最新更新