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

在c语言中,后置递增和后置递减运算符在运算符优先级规则中的位置是什么,c,operators,operator-precedence,C,Operators,Operator Precedence,根据本文中的信息,后增量和减量运算符居首位。上面写着“举个例子: foo=*p++ 这里,p作为表达式的副作用而递增,但foo的值为*(p++),而不是(*p++),因为一元运算符从右向左绑定” 但在做了这件事之后,这些链接中提到的信息几乎什么也没有发生 #include<stdio.h> #include<stdlib.h> int main() { int i = 1; int *iptr; iptr = &i; int num

根据本文中的信息,后增量和减量运算符居首位。上面写着“举个例子:

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: %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;
}
#包括
#包括
int main()
{
int i=1;
int*iptr;
iptr=&i;
int num=*iptr++;//1)在这个表达式中,“i”的值被分配给num。并且尝试对存储在*iptr中的地址进行后期递增作为副作用。
printf(“Num值:%d\n”,Num);
printf(“指针:%d\n”,*iptr);//2)不递增*iptr的地址。如果递增,则不会打印'i'的值,而是打印递增的地址本身。
printf(“Post increment:%d\n”,*iptr++);/3)将对*iptr的地址进行Post incremented(num的情况下不会发生这种情况)。但现在将打印'i'的值。
printf(“增量后:%d\n”,*iptr);//4)现在将显示存储在*iptr中的增量地址,因为没有为该地址分配值。
返回0;
}

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

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

对于数组中的指针,增量指针的解除限制是定义良好的

int array[] = {1, 2, 3};
int *iptr = &array[0];
int num = *iptr++;
此外,使用
%d
和取消引用操作符打印
iptr
是不正确的:在将
iptr
转换为
void*
后,您需要使用
%p
打印它,而无需取消引用:

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

现在一切都按预期进行()。

您如何知道没有看到任何效果?这是什么印刷品?所看到的效果与运算符优先级有什么关系?在(1)中,递增的是
iptr
,而不是
*iptr
不同意“将指针指向单个局部变量,递增指针会产生未定义的地址”。如果是,递增的指针不应被取消引用,但根据“一次过去”规则,指针本身是有效的,“指向非数组元素的对象的指针的行为与指向长度为1的数组的第一个元素的指针的行为相同”C11§6.5.6 7-8@chux您是对的,“一次过去”规则允许OP将指针递增一次。不过,第二个增量应该是UB。我编辑后对UB的声明更加保守。非常感谢。顺便说一句,提前祝贺120万美元。@chux非常感谢你!非常感谢你的努力。