简体   繁体   中英

Evaluation Order of Subscript Operator

Does there exist any order for evaluation of expressions in case of an array. If an expression E is of the form E1[E2], where E1 & E2 are also expressions, is the order of evaluation of E1 & 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's showing output as: 1243

I'v compiled it with gcc.

Thanks.

E1[E2] is equivalent of *(E1 + E2) .

And the Standard tells that "the order of evaluation of subexpressions and the order in which side effects take place are both unspecified". So, the order of evaluation of E1[E2] is not fixed.

N1256 :


...
3 The grouping of operators and operands is indicated by the syntax. 74) Except as specified later (for the function-call () , && , || , ?: , and comma operators), the order of evaluation of subexpressions and the order in which side effects take place are both unspecified.

So the short answer is "no"; for an expression like E1[E2] , the order in which the subexpressions E1 and E2 are evaluated is not fixed.

I hope you only ask this from curiosity and are not depending on this behaviour for something;

I don't have a C standard near me, but I don't see why you couldn't instead break up the operations into two separate statements, adding an explicit sequence point. You and other people might not remember what the correct order was supposed to be in the future, creating a maintenance issue.

int * the_array = E1;
the_array[E2];

//or

int the_index = E2;
E1[the_index];

//is much clearer

The evaluation order across the subscript operator is undefined . Let's give another example that isn't so obfuscated.

Issue: Consider the following expression:

f() + g() * h()

The precedence is quite clear; multiplication wins out over addition, as demonstrated by the corresponding parse tree:

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

the precedence table only tells us how terms are grouped, not the order in which they are evaluated. The only way to make the order predictable is to introduce what the C Standard calls sequence points . For example, the steps:

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

result in the same precedence as before, but with the functions being called in the guaranteed order g() , h() , and f() .

So in your example, you have to introduce sequence points to ensure that your printf statements are executed in the desired order.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM