我一直在努力理解以下 C 程序:
#include <stdio.h>
int arr[] = {1,2,3,4};
int count;
int incr(){
return ++count;
}
int main(){
arr[count++]=incr();
printf("%d %d",count,arr[count]);
return 0;
}
程序给出 1 2 作为 output ,我想不通的是为什么 count 的值在这里是 1 而不是 2(因为有两个增量)?
最佳答案
=
运算符的计算顺序在 arr[count++]=incr();
中未指定,因为两个操作数都试图修改同一个全局变量 count
根据计算顺序,不同编译器的结果会有所不同。
编辑
实际上该行为是未定义(这意味着任何事情都可能发生)因为"the prior value of the variable count
is not accessed (only) to determine the value to be stored."
关于c++ - 为什么这个输出?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5827707/