How can I (if it is possible at all) initialize multiple variables of different type in a C# for
loop? Example:
for (MyClass i = 0, int j = 1; j<3; j++,i++)
Example - Declaring multiple variables in a statementIf your variables are the same type, you can define multiple variables in one declaration statement. For example: int age, reach; In this example, two variables called age and reach would be defined as integers.
E2238 Multiple declaration for 'identifier' (C++)A function declared in two different ways. A label repeated in the same function. Some declaration repeated, other than an extern function or a simple variable.
You can assign the same value to multiple variables by using = consecutively. This is useful, for example, when initializing multiple variables to the same value. It is also possible to assign another value into one after assigning the same value.
Yes, I can declare multiple variables in a for-loop. And you, too, can now declare multiple variables, in a for-loop, as follows: Just separate the multiple variables in the initialization statement with commas.
It can't be done. Put one of the declarations before the loop:
MyClass i = 0; for (int j = 1; j < 3; j++, i++)
Or for symmetry, both of them:
MyClass i = 0; int j = 1; for (; j < 3; j++, i++)
It's also possible that one of the variables is more primary than the other. In that case it might be neater to have one be the loop variable, and deal with the other seperately, like this:
MyClass i = 0; for (int j = 0; j < 3; j++) { ... i++; }
Note that if i
and j
were of the same type, then you could declare them both in the for-loop:
for (int i = 0, j = 1; j < 3; j++, i++)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With