Skip to content

spec: (non?)evaluation of operand is unclear when ranging over pointer-to-array type #4644

Closed
@adonovan

Description

@adonovan
My understanding of the range statement is that if the type of the range operand is
*[n]T (i.e. a pointer-to-array type) and if only one iteration variable is present, then
the operand is not necessarily evaluated and the loop degenerates to:

  for i := 0; i < n; i++ { ... }

However the wording of the spec is somewhat ambiguous as to whether implementations may
or must perform this optimisation:

"The range expression is evaluated once before beginning the loop except if the
expression is an array, in which case, depending on the expression, it might not be
evaluated (see below). ... As a special case, if only the first iteration variable is
present, the range loop produces iteration values from 0 up to len(a) and does not index
into the array or slice itself."

But the spec doesn't say how evaluation or non-evaluation depends on the expression. 
Here are two plausible explanations:
1. It's unspecified and implementation-dependent.
2. Side effects such as function calls and channel ops must be observed, but
implementations may optimise away pure expressions such as composite literals, etc.

The test function testarrayptr1 at $GOROOT/test/range.go seems to require that the
implementation not perform this optimisation, and it appears that gc does not:

http://play.golang.org/p/Oi3pmY08s8

Can you clarify the intended behaviour?

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions