Commas in for loop
-
06-10-2020 - |
Question
Why is the following line producing errors?
for(int i = 0, int pos = 0, int next_pos = 0; i < 3; i++, pos = next_pos + 1) {
// …
}
error: expected unqualified-id before ‘int’
error: ‘pos’ was not declared in this scope
error: ‘next_pos’ was not declared in this scope
Compiler is g++.
Solution
You can have only one type of declaration per statement, so you only need one int:
for(int i = 0, pos = 0, next_pos = 0; i < 3; i++, pos = next_pos + 1)
OTHER TIPS
In a normal program:
int main()
{
int a=0,int b=0,int c=0;
return 0;
}
will never work and is not accepted.
This is what you are actually trying to do inside the for loop!
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow