简体   繁体   中英

parentheses inside for loop initialization

for (int i(0); i < 10; ++i) { ... }

Has the int i(0) syntax inside the for loop initializer always been allowed in standard C++?

It compiles fine with g++ -std=c++98 , but I don't trust compilers when it comes to standard details.

Yes. It's a simple variable declaration (a simple-declaration in language grammar) which was explicitly allowed in C++ for loop's for-init-statement (as opposed to C back then).

Especially, in the language grammar the following are equivalent (both are simple-declarations ):

int i(0);
int i = 0;

Here are the relevant parts of the syntax found in The C++ Programming Language , Appendix A:

iteration-statement:
    ...
    for (for-init-statement condition_opt; expression_opt) statement

for-init-statement:
    ...
    simple-declaration

simple-declaration:
    decl-specifier-seq_opt init-declarator-list_opt;

init-declarator-list:
    init-declarator
    init-declarator-list , init-declarator

init-declarator:
    declarator initializer_opt

initializer:
    = initializer_clause
    ( expression-list )

So yes, the for (int i(0); ... syntax has always been allowed in standard C++.

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