#include <iostream>
int main() {
for(int i = 0; i < 100; i++ && int a = 1; a < 100; a++){
std::cout<< a<< "This happens 100 times!\n";
}
}
main.cpp: In function ‘int main()’:
main.cpp:4:36: error: expected primary-expression before ‘int’
for(int i = 0; i < 100; i++ && int a = 1; a < 100; a++){
^~~
There's a lot of funny things you can do with a for loop, but the overall syntax looks like:
for ( declaration-or-expression(optional) ; declaration-or-expression(optional) ; expression(optional) )
The real issue is: i++ && int a = 1;
Even outside of a for loop, this doesn't make sense. You can't mix a variable declaration and an operation like && like that.
You could move the i++ part to the third section of the for loop (where the a++ is). But if you try to pack too much stuff into one line, then things just become unreadable.
#include <iostream>
int main() {
for ( int i = 0, a = 1; i < 100 && a < 100; ++i, ++a ) {
std::cout << a << " This happens 99 times!\n";
}
}
but for this trivial example:
1 2 3 4
for ( a = 1; a < 100; ++a ) {
int i = a - 1; // but i is unused
std::cout << a << " This happens 99 times!\n";
}
[EDIT]
1 2 3
int i = 0, a = 1 // is valid declaration of two int variables
i < 100 && a < 100 // is valid boolean expression
++i, ++a // is valid too, although the comma-operator is tricky and best avoided
Hint: You can edit your post, highlight your code and press the <> formatting button. This will not automatically indent your code. That part is up to you.
You can use the preview button at the bottom to see how it looks.
I found the second link to be the most help.
Yes. Using the , operator to separate them . for (int i = 0, j = 1; i < 10; i++)
You can also do: for (int i = 0, j = 1; i < 10; i++, j++)