25

Why does this C++ code not compile under VS2010:

for ( int a = 0, short b = 0; a < 10; ++a, ++b ) {}

while this one does:

short b = 0;
for ( int a = 0; a < 10; ++a, ++b ) {}

Is the declaration of two variables of different types inside the for-loop initializer prohibited? If so, how can you work around it?

Mechanical snail
  • 29,755
  • 14
  • 88
  • 113
grzkv
  • 2,599
  • 3
  • 26
  • 37
  • Looks like you say. Using the same type works: `for ( int a = 0, b = 0; a < 10; ++a, ++b ) {}` Hmm. Never noticed that before. – juergen d Dec 27 '11 at 12:41
  • Yes this is the "double loop" mechanism that came from the C language. Quite rare, though. Not very readable. – Raveline Dec 27 '11 at 12:45

5 Answers5

44

Yes, that is prohibited. Just as otherwise you cannot declare variables of differing types in one declaration statement (edit: modulo the declarator modifiers that @MrLister mentions). You can declare structs

for (struct { int a = 0; short b = 0; } d; d.a < 10; ++d.a, ++d.b ) {}

C++03 code:

for (struct { int a; short b; } d = { 0, 0 }; d.a < 10; ++d.a, ++d.b ) {}

Of course when all are 0, you can omit the initializers altogether and write = { }.

Johannes Schaub - litb
  • 496,577
  • 130
  • 894
  • 1,212
11

Nothing to do with the for loop. This also doesn't compile if you write int a = 0, short b = 0; outside of any loop.
So the answer is: it is always forbidden to declare two variables of different types in a single statement.

Edit: Oh, for the pedantic, I do realise that you can declare a base type and a pointer type in the same statement, for instance an int and an int pointer, so those would be different types, yes.
Hm, that makes me think. In a 32 bit environment, a pointer would be 4 bytes, just like an int, so you could use short a = 0, *b = 0; and then cast b to an int. Hm...

Mr Lister
  • 45,515
  • 15
  • 108
  • 150
1

What is prohibited is the ending of a statement with a comma as you do in int a = 0, short ...

If you want to use this notation then bothe variable muss have the same type int i = 0, s = 0;

A4L
  • 17,353
  • 6
  • 49
  • 70
0

You can only declare one type in for statement. So the second code is the usable one.

RonzyFonzy
  • 698
  • 10
  • 16
0

You can't declare a variable into the while condition of the for (the comprobation step).

for ( a = 0, short b = 0; a < 10; ++a, ++b ) {}

that's neither works.

Shafik Yaghmour
  • 154,301
  • 39
  • 440
  • 740
Leandro Bardelli
  • 10,561
  • 15
  • 79
  • 116