为什么交换变量名会改变 C 程序的输出?

Why does exchanging variable name changes output of C program?

我尝试了这个数组示例,post 对其元素进行增量/预增量

#include<stdio.h>

int main()
{
    int j[5] = {5, 1, 15, 20, 25};
    int k , l, m, n;

    n = ++j[1];
    k = ++j[1];
    l = j[1]++;
    m = j[k++];

    printf("\n%d, %d, %d, %d", n, k, l, m );

    return 0;
}

这里的输出是:

2, 4, 3, 20

如果我改变 n 和 k 的顺序 即而不是

n = ++j[1];
k = ++j[1];

我写

k = ++j[1];
n = ++j[1];

输出变为:

3, 3, 3, 15

我在 windows10 的 mingw 编译器和 Kali Linux 的 GCC 上试过这个... 同样的问题。

就像取不同的变量名会改变程序的输出一样。 可能是什么原因?

谢谢大家帮我解答这个问题。

我没有考虑 k 的最后一个 post 增量。

结果会和我改变的一样

m=j[k++]

m = j[n++]

他们为什么不呢? knm 的值取决于它们在代码中的位置。

例如,

 m = j[k++];

这将受到 k 当前 值的影响。

添加一些关于 pre 和 post 增量运算符的内容,引用 C11

  • 章节 §6.5.3.1,预增量

    The value of the operand of the prefix ++ operator is incremented. The result is the new value of the operand after incrementation. [...]

  • 章节 §6.5.2.4,post-增量

    The result of the postfix ++ operator is the value of the operand. As a side effect, the value of the operand object is incremented (that is, the value 1 of the appropriate type is added to it). [....]

我添加了一些打印语句,以检查每个语句后值如何受到影响。您还可以打印整个数组以更直观地看到变化。

int j[5] = {5, 1, 15, 20, 25};
int k , l, m, n;

printf("j[1] = %d\n", j[1]);

k = ++j[1];
printf("j[1] = %d, k = %d\n", j[1], k);
n = ++j[1];
printf("j[1] = %d, n = %d\n", j[1], n);
l = j[1]++;
printf("j[1] = %d, l = %d\n", j[1], l);
m = j[k++];
printf("m= %d, k = %d\n", m, k);

printf("\n%d, %d, %d, %d", n, k, l, m );

输出为:

j[1] = 1
j[1] = 2, k = 2
j[1] = 3, n = 3
j[1] = 4, l = 3
m= 15, k = 3

3, 3, 3, 15

第一种情况:

n = ++j[1]; //j[1] is incremented and is now 2, so n is 2
k = ++j[1]; //j[1] is incremented again and is now 3, so k is 3
l = j[1]++; //j[1] is incremented yet again and is now 4, but l is 3 as it is post-increment
m = j[k++]; //m  is j[3] which is 20, and k will become 4 as it is post-incremented

所以 n, k, l, m 的输出将是 2, 4, 3, 20

第二种情况:

k = ++j[1]; //j[1] is incremented and is now 2, so k is 2
n = ++j[1]; //j[1] is incremented again and is now 3, so n is 3
l = j[1]++; //j[1] is incremented again and is now 3, but l is 3
m = j[k++]; //m  is j[2] which is 15, and k will become 3 as it is post-incremented

所以 n, k, l, m 的输出将是 3, 3, 3, 15

其实并没有那么复杂 int j[5] = {5, 1, 15, 20, 25};

n = ++j[1];
// n=2 j[1]=2

k = ++j[1];
// k=3 j[1]=3

l = j[1]++;
// l=3 j[1]=4

m = j[k++];
// since k=3, k becomes 4 but m is assigned j[3] which is 20

让我们看看另一个案例

int j[5] = {5, 1, 15, 20, 25};

k = ++j[1];
// k=2 j[1]=2

n = ++j[1];
// n=3 j[1]=3

l = j[1]++;
// l=3 j[1]=4

m = j[k++];
// since k=2, k becomes 3 but m is assigned j[2] which is 15