括号内的运算符优先级

Operator Precedence Within Parenthesis

我对下面代码的理解是,ip在第二个printf语句中递增;然后,检索 *ip 指向的值。但输出显示不同。

#include <stdlib.h>
#include <stdio.h>

int main()
{
    int i[2] = { 1, 4 };
    int *ip;

    ip = i;

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

    return 0;
}

输出:

1
1
4

然后,通过更改为预递增运算符,++ip,出现了预期的结果。

带预增量的代码

#include <stdlib.h>
#include <stdio.h>

int main()
{
    int i[2] = { 1, 4 };
    int *ip;

    ip = i;

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

    return 0;
}

输出:

1
4
4

我对 C 中运算符优先级的理解是 ()* 运算符具有更高的优先级。话虽如此,为什么 post 递增运算符 ip++ 没有首先求值 - 因为它在 ().

不管评估顺序如何,++ip 在返回 ip 的新值之前递增,而 ip++ returns 返回 ip 的旧值然后递增。 (或者,如果您愿意,可以保存旧值,递增 ip,然后 returns 旧值。)

这就是pre和post-increment的区别。

在你的两个例子中,括号都是多余的。

My understanding of the following code is that ip is incremented in the second printf statement; then, the value pointed to by *ip is retrieved.

其实是反过来的,看第二个printf的注释代码:printf("%d\n", *(ip++));

int i[2] = { 1, 4 };
int *ip;

ip = i; // ip points to the first array element i[0]

printf("%d\n", *ip);        // fetch ip and printf it (i[0] = 1)
printf("%d\n", *(ip++));    // 1) fetch ip and printf it (i[0] = 1), then 2) increment ip, which now points to i[1]
printf("%d\n", *ip);        // fetch ip and printf it (i[1] = 4)

首先,pre- 和 post-increment 运算符都比 * 运算符具有更高的优先级,因此 *ip++ 完全等同于 *(ip++),并且 *++ip 也是完全等同于 *(++ip).

然后我们看一下pre-和post-increment运算符的区别:++i的值等于i+1,而i++等于i,尽管在任何一种情况下,i 的值都会在计算 *-increment 运算符后增加 1。