Evaluation of the subscript operator

Is there any way to evaluate expressions in the case of an array. If the expression E has the form E1 [E2], where E1 and E2 are also expressions, is the evaluation order of E1 and E2 fixed?

Here is my code:

#include<stdio.h>
int main(){

    int a[5] = {1,2,3,4,5}; 
    (a + printf("1"))[printf("2")];
    (printf("3"))[a + printf("4")];

    return 0;
}   

It shows the result as: 1 243

I'v compiled it with gcc.

Thank.

+5
source share
4 answers

E1[E2]equivalent to *(E1 + E2).

And the standard says that "the order in which subexpressions are evaluated and the order in which side effects occur are not defined." Thus, the evaluation procedure is E1[E2]not fixed.

+7
source

N1256 :

6.5
...
3 . 74) , ( - (), &&, ||, ?: ), , , .

, - ""; , E1[E2], , E1 E2, .

+3

, -,

C , , , . , , , , .

int * the_array = E1;
the_array[E2];

//or

int the_index = E2;
E1[the_index];

//is much clearer
+2

undefined. , .

: :

f() + g() * h()

; , :

       +
    /     \
   /       \
  f()       *
  /          \
  /           \
 g()           h()

, , , . - , C Standard . , :

x = g();
x = x * h();
x = x + f();

, , , g(), h() f().

, , , printf .

+2
source

All Articles