When I run the following code, I get the output: 0 0 2 0 0
int main(){
static int var[5];
int count=0;
var[++count]=++count;
for(count=0;count<5;count++)
{
printf("%d ",var[count]);
}
return 0;
}
When I run the following code, I get the output: 0 0 2 0 0
int main(){
static int var[5];
int count=0;
var[++count]=++count;
for(count=0;count<5;count++)
{
printf("%d ",var[count]);
}
return 0;
}
The statement var[++count]=++count;
induces undefined behavior according to the C17 standard 6.5.2:
If a side effect on a scalar object is unsequenced relative to either a different side effect on the same scalar object or a value computation using the value of the same scalar object, the behavior is undefined. If there are multiple allowable orderings of the subexpressions of an expression, the behavior is undefined if such an unsequenced side effect occurs in any of the orderings.)
Thus, for each unique variable, it holds that if it is pre-incremented, then its value may not be used elsewhere in that expression. The result will be that the variable is incremented first, and its incremented value is then used in the expression.
The code is technically undefined behavior. What (probably) happened in practice, is that count
was incremented twice and then used both as an index and a value.