Declaration inside while

Why I can't declare variable inside while loop like if or for loops?

1
2
3
4
5
6
7
8
9
10
11
12
int main() {
//sum = 2+4+6+8+...
    int sum = 0;

    while(int x<=100){
        x = 2;
        cout << x;
        sum += x;
        x += 2;
    }

}
closed account (48T7M4Gy)
Because the variable can only be declared once. Why would you want to declare it multiple times anyway?
But x just declared once in ( )
Last edited on
and is automatic.

int x <= 100 is not right

do instead

int x = 2;
while(x <= 100)
{
cout << x;
sum += 2;
x += 2;
}

but the compiler is probably gonna unroll it.
closed account (48T7M4Gy)
Correct, I tested it and it is not the multiple aspect, it's the invalid declaration. int x = 2 is a valid statement so presumably the while compilation is valid despite the declaration problem if it was elsewhere. We live and learn.
Thanks guys, I knew how should I correct it but my question was about why I can't use declaration in a while( ) like for() or if ()?!
Last edited on
closed account (48T7M4Gy)
You can use a declaration there but it appears to me it will not be interpreted as a declaration. It will be interpreted as a true/false proposition and int x = 100 is true whereas int x <= 100 is simply an error so it's neither true nor false.
Topic archived. No new replies allowed.