[英]What place does post increment and post decrement operators have in the rules of operator precedence in c language
根据此链接中的信息,后递增和递减运算符位于第一位。 并且此链接显示 “以以下示例为例:
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;
}
在以上实验中,仅在语句终止后才能看到后增加的效果。 但是,如果在赋值运算符的右侧操作数上执行了后递增,则即使在语句终止之后也看不到任何效果。 EG 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 -----------^
现在一切都按预期进行( 演示 )。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.