Home > Back-end >  How to properly use the for-range statements syntax in C ?
How to properly use the for-range statements syntax in C ?

Time:09-22

iteration-statement:
    while ( condition ) statement
    do statement while ( expression ) ;
    for ( init-statement conditionopt ; expressionopt ) statement
    for ( init-statementopt for-range-declaration : for-range-initializer ) statement
for-range-declaration:
    attribute-specifier-seqopt decl-specifier-seq declarator
    attribute-specifier-seqopt decl-specifier-seq ref-qualifieropt [ identifier-list ]
for-range-initializer:
    expr-or-braced-init-list

The syntax above is given by C ISO. I have seen a ton of examples using the classic approach for a for-range statement:

#include <iostream>
using namespace std;
int main() {
    int a[5] = { 1,2,3,4,5 };
    for (int i : a) { cout << i << endl; }
}

But I'm not finding how to use for-range-declaration as attribute-specifier-seqopt decl-specifier-seq ref-qualifieropt [ identifier-list ]. How does it work in this case? Could you provide an example?

CodePudding user response:

This part of the grammar

attribute-specifier-seqopt decl-specifier-seq ref-qualifieropt [ identifier-list ]

is to allow for structured bindings in a loop. e.g. you could do something like this:

struct S { int i,j; };
std::vector<S> v;
for (auto [a, b] : v)
  // ... a and b simply refer to i and j

Note that the identifier-list indicates that the names a and b just refer to the members of the struct.

  • Related