I don't understand why it is allowed to declare variables in a while or for loops. For example this is allowed (or at least compiles ??)

for(int i = 3; i > 0; i--) {
int d;
}

and this will give you a compiler error;

int d;
int d;
int d;

Why?? Is it just my compiler being kind (If it is soo, then I thin the compiler is too kind!) or is it legal for some other reason?

If you want the compiler to be "unkind", turn on all warnings with the -Wall flag and then turn on the -Werror flag, which turns warnings into errors and aborts. Thus this will not compile using the following command...

g++ unused_var.cpp -Wall -Werror
int main()
{
    for(int i = 0; i < 3; i++)
    {
        int d;
    }

    return 0;
}

because -Wall turned on this warning flag... -Wunused-variable


It's a warning, not an error. Declaring d three times is an error in the SAME SCOPE. The compiler has no idea how to build its symbol table because all three of your d varaibles are in the same scope. The brackets add a scope level.

Declaring d INSIDE of brackets is perfectly fine as long as you only do it once "per scope".

int main()
{

    {
        int d = 6;
        {
            int d = 8;
            {
                int d = 10;
            }
        }
    }

    return 0;
}

That's three separate integers. Three different scopes. Perfectly legal. They don't interfere with each other. Declaring a new variable inside the loop creates a new scope.
The compiler isn't being "nice". It's assuming you are doing something perfectly legal intentionally.

This is illegal.

int main()
{

    {
        int d = 6;
        {
            int d = 8;
            int d = 10;
        }
    }

    return 0;
}

Two d's are in the same scope.

This is legal until you uncomment line 16, at which point you'll get a scope error. It will display 9 because the "d" that lines 14 and 15 refer to is the "d" declared on line 10.

#include <iostream>
using namespace std;

int main()
{

    {
        int d = 6;
        {
            int d = 8;
            {
                int e = 10;
            }
            d++;
            cout << d; // displays 9
            //e = 11;
        }
    }

    return 0;
}

http://easycplusplus.com/cpp/cpptutorial28a.html
http://gcc.gnu.org/onlinedocs/gcc/Warning-Options.html

Thanks for explaining!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.