0
Can someone explain me output of the code?
#include <stdio.h> int main() { char s[12]="SOLOLEARN"; int i = 1; char ch1 = ++i[s]; char ch2 = i++[s]; printf("%c",ch1); printf("\t%c",ch2); return 0; } // Output :- P P
1 Resposta
+ 2
the compiler converts the array operation in pointers before accessing the array elements.
therefore:
array[index] will evaluate to → *(array+index).
and index[array] will evaluate to → *(index + array) which is the same as *(array + index) "addition is commutative".
in your case:
# char ch1 = ++i[s];
due to the operator precedence the expression ++i[s] is equivalent to:
++(i[s]) which evaluate to ++(*(i+s)) == ++(*(s+i)) which increments the value of s[i] before it has been evaluated.
now s[i] evaluate to 'P' ( next character after 'O' is 'P' ).
# char ch2 = i++[s];
On the other hand the expression i++[s] is equivalent to:
( i++[s] ) which will evaluate to *( i++ + s) == *(s + i++) which evaluate the expression to s[i], before i has been incremented.