declaring multiple vars in a For loop

Uber noob question, it’s a simple answer, but if it’s yes, I’m unsure of the syntax to make it work. And again, searching yields too many results (or no results if the answer is no!).

I want to declare 2 vars (ints) in the for loop command, and have it increment both of them, but only test one.

Example:

for (foo= 1  bar=34; foo <=76 ; foo++ bar++)
{
   //Do some Foobarring here

}

I am currently using:

bar= 34
for (foo=1; foo<=76; foo++)
{
  //More foobarring
  bar++;
}

But to me it’s ugly. Is there a way to declare both within a loop? I doubt there’s any performance gains from this, it’s just purely for aesthetics.

Thanks!

1 Like
for (foo= 1,  bar=34; foo <=76 ; foo++, bar++)
1 Like

Sweet, thanks.

1 Like

The comma operator is your friend.

You can also declare the vars in the loop itself as long as you do not need them after the loop.

 for( int foo = 1, bar = 34 ; foo <= 76 ; ++foo, ++bar){
     //Do some Foobarring here
  }

I was just going to ask that, but when I tried:

for( foo = 1 , int bar = 34; etc etc.....

It threw an error…

Actual line of code:

for(x = 0, int y = 8-buf.length(); x < buf.length() ; x++, y++)
{......

Errors:

Binary_Counter_Pot.ino: In function 'void loop()':
Binary_Counter_Pot:44: error: expected primary-expression before 'int'
Binary_Counter_Pot:44: error: expected `;' before 'int'
Binary_Counter_Pot:44: error: 'y' was not declared in this scope

Do constructors have to come first?

Thanks for the help folks! Great community!

EDIT: Thanks for the link to the comma, been looking for that, never thought to check wikipedia lol.

EDIT2: Guess I answered my own question, swapped their positions in the statement and it worked.

Marmotjr:
EDIT2: Guess I answered my own question, swapped their positions in the statement and it worked.

If you strip the declaration out of the loop and remove the initialization, it may be more obvious why it didn’t work. You can declare multiple variables of the same type using a comma as a separator, however it is not a comma operator ( x++, y++ is using the operator ).

x, int y;

//As opposed to

int x, y;