You can, obviously, put a variable declaration in a for loop:
for (int i = 0; ...
and I’ve noticed that you can do the same thing in if and switch statements as well:
if ((int i = f()) != 0) ... switch (int ch = stream.get()) ...
But when I try to do the same thing in a while loop:
while ((int ch = stream.get()) != -1) ...
The compiler (VC++ 9.0) does not like it at all.
Is this compliant behavior? Is there a reason for it?
EDIT: I found I can do this:
while (int ch = stream.get() != -1) ...
but because of precedence rules, that’s interpreted as:
while (int ch = (stream.get() != -1)) ...
which is not what I want.
The grammar for a condition in the ’03 standard is defined as follows:
The above will therefore only allow conditions such as:
The standard allows the condition to declare a variable, however, they have done so by adding a new grammar rule called ‘condition’ that can be an expression or a declarator with an initializer. The result is that just because you are in the condition of an
if,for,while, orswitchdoes not mean that you can declare a variable inside an expression.