1

Some languages support using getArray()[0] instead of arr=getArray();arr[0]. What is this called?

Leo Jiang
  • 24,497
  • 49
  • 154
  • 284
  • I'm pretty sure, this doesn't have a special name in c++. Might be a stupid question (im only familiar with c++ like languages), but what programming languages don't support it? – MikeMB Apr 04 '15 at 00:51
  • PHP doesn't support it. I remember reading an article about how Javascript supports this and there was a special name for it. – Leo Jiang Apr 04 '15 at 00:57
  • PHP does support it now: [example](https://ideone.com/xIv5Gw). [The answers to this question](http://stackoverflow.com/questions/1459377/access-array-returned-by-a-function-in-php) suggests it became valid in PHP 5.4 – Phylogenesis Apr 04 '15 at 01:01
  • Oops, I'm so used to not using it in PHP, so I never bothered checking to see if I can use it now. I guess it can be called something like "array-accessible function return value." – Leo Jiang Apr 04 '15 at 01:07
  • Yes, I remember being quite pleased when it became available. That and being able to use `[]` instead of `Array()` for an array literal. – Phylogenesis Apr 04 '15 at 01:16

1 Answers1

0

Things like getArray()[0] work as a result of the language's grammar (and semantics) permitting arbitrary expressions (which compute an array) to have array accesses appended onto them.

Java calls the relevant portion of the grammar an array access expression.

ArrayAccess:
    ExpressionName [ Expression ]
    PrimaryNoNewArray [ Expression ]

(If you're wondering about the PrimaryNoNewArray rule, the NoNewArray part is there because multidimensional array creation in Java looks like new int[10][5]. You don't want that second [ ] to be confused with an array access.)

In C99, it's part of the postfix-expression rule:

 postfix-expression:
     ...
     postfix-expression "[" expression "]"
     ...

If the grammar doesn't allow arbitrary expressions to the left of the [, then you end up in the situation that (apparently?) PHP was in.

Jay Kominek
  • 8,674
  • 1
  • 34
  • 51