Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 610
Vipin Pillai Avatar asked Sep 26 '11 14:09

Vipin Pillai


People also ask

What is the order of evaluation of the operators?

Only the sequential-evaluation ( , ), logical-AND ( && ), logical-OR ( || ), conditional-expression ( ? : ), and function-call operators constitute sequence points, and therefore guarantee a particular order of evaluation for their operands.

Does the order operators are evaluated in matter?

Yes, of course it does matter - js is evaluated from left to right, and the || operator does short-circuit.

What is the subscript operator?

The subscript operator is defined as square brackets [] . It is used to access the elements of string, list tuple, and so on. Let's discuss the syntax with an example: <given string>[<index>] The given string is the string you want to examine and the index is the position of the character you want to obtain.

What is subscript operator in C?

The subscript operator is commutative. Therefore, the expressions array[index] and index[array] are guaranteed to be equivalent as long as the subscript operator is not overloaded (see Overloaded Operators). The first form is the most common coding practice, but either works.


2 Answers

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.

like image 101
qehgt Avatar answered Sep 17 '22 23:09

qehgt


N1256:

6.5 Expressions
...
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.

like image 32
John Bode Avatar answered Sep 18 '22 23:09

John Bode