I ran the following code through gcc based C compiler:
int main() {
int i = 0; // Line 1
static int a[10]; // Line 2
a[i] = ++i; // Line 3
printf("%d %d", a[0], a[1]); // Line 4
return 0; // Line 5
}
As per the precedence table provided in the textbook "The C Programming Language by Brian Kernighan and Dennis Ritchie" and the website: https://en.cppreference.com/w/c/language/operator_precedence, the precedence of square brackets (array subscript operator) is higher than that of prefix operator ++.
On running the program, the output i receive is: a[1] = 1.
I don't understand why the sequence of operations is not as follows:
- a[0] (put i = 0)
- ++i (increment i by 1)
- a[0] = 1 (assign value of i to a[0])
and instead works as
- ++i (increment i by 1)
- a[1] (put i = 1)
- a[1] = 1 (assign value of i to a[1])
breaking the precedence rule. Please help me know where I'm going wrong.