开发者

printf behavior

Take int ptr={10,20,30,40,50} I understand that

print("%d", *ptr++);

in such a statement evaluation of operators is from right to left. Hence in *ptr++ the ++ will get evaluated first and then ptr and then * So to confirm the same I wrote a program

#include<stdio.h>
int main()
{
        int array[] = { 10, 20, 30, 40, 50 };
        int *q1 = array;
        printf("q1 = %p\n",q1);
      printf("*q1++ = %d\n"开发者_运维技巧,*q1++);
        printf("q1 = %p\n",q1);
      printf("*q1++ = %d\n",*q1);
}

The output of above program is different than the expected operator precedence by above logic. The output I got is

q1 = 0x7ffffcff02e0
*q1++ = 10
q1 = 0x7ffffcff02e4
*q1++ = 20

but I was expecting

q1 = 0x7ffffcff02e0
*q1++ = 20
q1 = 0x7ffffcff02e4
*q1++ = 20

so did the operator precedence not happened right to left? Or there is some thing wrong in my understanding?

UPDATE

Now here is the thing.Even if I put these brackets as mentioned so that *(ptr++) gets executed the output does not change here is new code

#include<stdio.h>
int main()
{
        int array[] = { 10, 20, 30, 40, 50 };
        int *q1 = array;
        printf("q1 = %p\n",q1);
      printf("*q1++ = %d\n",*(q1++));// note the braces here *(q1++) so that () get evaluated 
        printf("q1 = %p\n",q1);
      printf("*q1++ = %d\n",*q1);
}

The result is still the same note the use of braces as you mentioned. Still the output is

q1 = 0x7fff043f2120
*q1++ = 10 <-- I expected *q1++ = 20//since I used braces ()
q1 = 0x7fff043f2124
*q1++ = 20

So even after I used braces *(ptr++) that operation ++ was still executed after the current line was executed.So did curly brace () not work? Or it was not given preferences over post increment thing?


No, operators don't get evaluated right to left. There is an operator precedence table that gives the order.

However, this is not the reason for the behavior you are seeing. The reason is that you are using the post-increment operator, which means that in *q1++ the pointer dereference happens on the value that of q1 had before the addition.

If you change the code to read *(++q1) (pre-increment operator) you would see the behavior you expect.


++ on the right returns the value before it gets evaluated.

printf("*q1++ = %d\n",*q1++);

is the same as

printf("*q1++ = %d\n",*q1);
++q1;


The statement *ptr++; will evaluate the value that ptr points to first, and then increment ptr. To increment first, use *++ptr;.


Having the ++ after the variable name is definitionally a post-increment operation meaning the pointer is advanced after the expression is evaluated.

x = *q++;

is the same as:

x = *q;
++q;

The pre-increment equivalent is:

x = *++q;

which would be:

++q;
x = *q;
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜