Array subscript [] in C is listed as having higher precedence than prefix increment.
Having following simple program:
#include <stdio.h>
int main()
{
char testArr[] = "asdfgh";
int a = 0;
printf("element is %c\n",testArr[++a]);
}
Why is s printed instead of a? The way as I see things, [] should have been applied first. Which means that the first element 0 of the testArr should have been displayed and not the element 1.
The subscript operator is defined the following way
postfix-expression [ expression ]
So to apply the subscript operator the compiler shall calculate the expression in the square braces (along with the postfix expression) to get the value of the expression.
From the C Standard (6.5.2.1 Array subscripting)
2 A postfix expression followed by an expression in square brackets [] is a subscripted designation of an element of an array object. The definition of the subscript operator [] is that E1[E2] is identical to (*((E1)+(E2))). Because of the conversion rules that apply to the binary + operator, if E1 is an array object (equivalently, a pointer to the initial element of an array object) and E2 is an integer, E1[E2] designates the E2-th element of E1 (counting from zero).
To make it more clear consider a simple code snippet
int i = 0;
int j = 1;
printf("element is %c\n",testArr[i + j]);
How the compiler can determine the index without calculation the expression i + j
?
That is the subscript operator is composed from two subexpressions that are evaluated to get their values.
Your question is reasonable if to consider the following expression
++testArr[++a]
or even the following expression
++a[testArr]
In this case due to the operator precedence the first expression is equivalent to
++( testArr[++a] )
and the second one is equivalent to
++( a[testArr] )
So the subscript operator including its subexpression in square braces ++a
or testArr
evaluates first and after that the unary operator evaluates.
On the other hand if to use the postfix increment like
a++[testArr]
then the expression is equivalent to
( a++[testArr] )
that is it is just the subscript operator that follows its own definition form
a++ [ testArr ]
postfix-expression [ expression ]
When you write
testArr[++a]
C will look at the index in the array given by the value of the expression ++a
. Regardless of the operator precedence between []
and ++
, the value of the expression ++a
is one greater than the value a
had before the expression was initially evaluated, which is why you're seeing the character at index 1 rather than the character at index 0.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With