简体   繁体   中英

How many variables can I initialize in the initialization of a for statement?

A simple for statement would be:

 for(int i = 0/*A Optional*/; i < 10/*B Optional*/; i++/*C Optional*/) {
 }

Now how many variables can I initialize in the initialization code(A) of the for statement? Also how would I initialize these variables in the initialization code(A) of the for statement?

As many as you care to write, but declaration is restricted to the same type. (For just initialization see the expansion below and Wugs answer.)

for (int a = 1, b = 2, c = 3 ; ; ) {
    break;
}

The (optional) ForInit section can be:

  1. If the ForInit code is a list of statement expressions (§14.8), the expressions are evaluated in sequence from left to right; their values, if any, are discarded.

  2. If the ForInit code is a local variable declaration , it is executed as if it were a local variable declaration statement (§14.4) appearing in a block.

  3. If the ForInit part is not present , no action is taken.

The example code above with declarations is of the form for(LocalVariableDeclaration;;) .

You can initialize as many as you want of any type, but should you use an inline declaration, all declared variables must be of the same type, as pst sort of mentioned.

for (int i = 1, j = 0, k = -1; ; );

string s;
double d;

for (s = "", d = 1.5; ; );

You can separate statements in a for loop with commas, so you can initialize as many variables as you want. If you wanted to initialize several variables, your for loop would look like this:

 for(int i = 0, x = 1, d = 2; i < 10; i++, x++) {
 }

They do have to be of the same type.

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