Question: This code illustrates something that I think should be treated as bad practice, and elicit warnings from a compiler about redefining or masking a variable:

```
#include <iostream>

int *a;

int* f()
{
  int *a = new int;
  return a;
}

int main()
{
  std::cout << a << std::endl << f() << std::endl;
  return 0;
}

```

Its output (compiled with g++):

```
0
0x602010

```

I've looked at a couple references (Stroustrup and The Complete C++ Reference) and can't find anything about when and why this is allowed. I know that it's not within a single local scope, though.

When and why is this allowed? Is there a good use for this construct? How can I get g++ to warn me about it? Do other compilers squawk about it?

Answer: 
This is perfectly valid, but I think that with `-Wall` you only get a warning when you shadow a parameter.

If you want warnings when you shadow **any** type of variable, You can use this, from the `g++` manual page:

```
   -Wshadow
       Warn whenever a local variable shadows another local variable, 
       parameter or global variable or whenever a built-in function is 
       shadowed.

```

Note that `-Wshadow` isn't included in `-Wall` by default.
As others have mentioned, this is perfectly legal, and is unambiguous to the compiler.

However, it's one of many features in programming languages which has the potential to cause confusion or hard-to-find bugs. Since it would be trivial to give different names to each of these variables, for the sake of clarity, I'd always suggest doing so.