declaring variables inside while loop illegal?

R

Roy Smith

The following code appears to be illegal:

while ((int c = getchar()) != EOF) {
putchar (c);
}

I tried it on two different compilers (Sun workshop and gcc), and both
give some variation on syntax error at "int c =". The very similar:

for (int c = getchar(); c != EOF; c = getchar()) {
putchar (c);
}

compiles fine. What's going on here?
 
A

Artie Gold

Roy said:
The following code appears to be illegal:

while ((int c = getchar()) != EOF) {
putchar (c);
}

Correct. It is not legal.
I tried it on two different compilers (Sun workshop and gcc), and both
give some variation on syntax error at "int c =". The very similar:

for (int c = getchar(); c != EOF; c = getchar()) {
putchar (c);
}

compiles fine. What's going on here?

Also correct. It is legal. It's just the way the language is defined.

HTH,
--ag
 
M

Mark P

Artie said:
Correct. It is not legal.

Actually isn't the illegal bit not the declaration but the attempt to
use the declaration as an argument to !=? That is, it would be legal to
write:

while (int c = getchar()) {
putchar (c);
}

(Although not likely to do what the OP wants since EOF will evaluate to
true.)

-Mark
 
A

aprilend

i think the question is because of the declaration and not the attempt
to use the declaration as an argument to !=.
that is,it would be legal to write as following:
int c;
if((c=getchar())!=EOF)
putchar(c);

-zhanys
 
J

Jonathan Mcdougall

Roy said:
The following code appears to be illegal:

while ((int c = getchar()) != EOF) {
putchar (c);
}

You can do

while (int c = getchar())
{
}

The statement "int c=getchar()" has the value of "c" after its
initialization, but there is no way in the language to use this value.
Let's call that "dark matter".

You must find another way.

Jonathan
 
B

Bo Persson

Mark P said:
Actually isn't the illegal bit not the declaration but the attempt
to use the declaration as an argument to !=? That is, it would be
legal to write:

while (int c = getchar()) {
putchar (c);
}

Yes. The C++ syntax has a special case for 'condition', which has two
alternative forms:

1. expression
2. type-specifier-seq declarator = assignment-expression

meaning that you can declare a variable *directly* inside the
while/if/for/switch, but not elsewhere. The problem here is that '(int
c = getchar())' does not match syntax #2, so must be #1 - an
expression. And you cannot declare a variable in a general expression.


Bo Persson
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,581
Members
45,057
Latest member
KetoBeezACVGummies

Latest Threads

Top