views:

186

answers:

5

I thought one could initialize several variables in a for loop:

for (int i = 0, char* ptr = bam; i < 10; i++) { ... }

But I just found out that this is not possible, gcc gives the following error:

error: expected unqualified-id before 'char'

Is it really true that you can't initialize variables of different types in a for loop?

+3  A: 

try this:

int i;
char* ptr;
for (i = 0, ptr = bam; i < 10; i++) { ... }
Gary
+7  A: 

It's true that you can't simultaneously declare and initialize declarators of different types. But this isn't specific to for loops. You'll get an error if you do:

int i = 0, char *ptr = bam;

too. The first clause of a for loop can be (C99 §6.8.5.3) "a declaration" or a "void expression". Note that you can do:

int i = 0, *j = NULL;
for(int i = 0, *j = NULL;;){}

because i and *j are both of type int. The exact syntax for a declaration is given in §6.7

Matthew Flaschen
A: 

According to http://linuxsoftware.co.nz/cppgrammar.html#for-init-statement you can get only simple declaration or an expression (which is not permitted to contain declaration) in the for-init statement. That means the answer is no (if I analyzed the BNF correctly :) )

dark_charlie
+3  A: 

If you really need the variables to stay in the scope of the loop you could write

{ char* ptr = bam; for (int i = 0; i < 10; i++) { ... } }

It's a bit ugly, but works.

Axel Gneiting
+8  A: 

You can (but generally shouldn't) use an local struct type.

for ( struct { int i; char* ptr; } loopy = { 0, bam };
      loopy.i < 10 && * loopy.ptr != 0;
      ++ loopy.i, ++ loopy.ptr )
    { ... }
Potatoswatter
Ugly as hell, but effective.
Stephen Canon
Wow; I've never seen that before. And I'm sure teammates would kill me if I ever used it, but I'm tempted
Michael Mrozek
+1: very eclectic. Not something I would do but it reveals the underlying language semantics very nicely.
Amardeep
Clever. In practice, though, I'd prefer Axel Gneiting's approach.
jamesdlin
When people say, "just because you *can* do it doesn't mean you *should* ", they're talking about stuff like this. It works, though.
John Bode
That's so ugly I really want to vote it down but I can't because it works. God knows why anybody voted it *up* though. I'll have to find out if any of them work for my company and make sure they get fired.
JeremyP
@Jeremy: I don't blame you, but thanks for the restraint. I'm blown away by the positive response to this.
Potatoswatter
@Potatoswatter: It has a certain style, a bit like Angler fish. They're really ugly, but people are fascinated by them.
JeremyP