tags:

views:

104

answers:

5

Can we declare a variable in both the inner and the outer block of my program?Why it is called a bad practice if programatically it doesn't create any problem..

+2  A: 

becouse you hide a variable in a scope - and that a good way to make mistakes. In small programs you could remember which variable is global/local - in more complicated don't.

nilphilus
+3  A: 

The source code will be hard to understand, that's the problem, but it is legal.

MSalters
+2  A: 

You can declare variables either in functions (local variables), or outside functions (global variables). You should generally minimize the scope of a variable, as this makes the code easier to understand.

For example, if you're modifying the value of a global variable in one function, and call another function which, for unrelated reasons, also happens to modify that variable, the resulting code might do things that you're not expecting and which someone reading your code wouldn't expect (let alone if you were to then try parallelising that code...)

Jivlain
+3  A: 

In C, variables are lexically scoped, which means that at any given point in your code, the compiler knows which actual variable is being referred to by a given name. The problem is that if you have two variables named foo, (a) you might not remember which is which, and (b) you can't refer to the outer foo when you're in the inner foo's scope.

In particular:

void MyFunction()
{
    int foo = 1;
    printf("%d", foo); // prints "1"

    // create a new scope...
    if (whatever)
    {
        int foo = 2;
        printf("%d", foo); // prints "2"
        foo = 3;
        printf("%d", foo); // prints "3"
    }

    printf("%d", foo); // prints "1"
}

Now, just imagine that the whatever block were long and complicated... when you get to foo = 3, let's say the top of the block isn't on the screen, but you know that MyFunction has a function-wide variable named foo. The only problem is that you're wrong, you're only setting the value of the "inner" foo. From the compiler's point-of-view it's obvious... because the inner foo hides the outer one completely. That's why it's considered a bad practice.

You may want to read http://en.wikipedia.org/wiki/Scope_(programming) to learn more about lexical scoping.

JaredReisinger
+1  A: 

This is called variable shadowing, it has its advantages for small things like constructors, but in the long run it can lead to problems:

  • code is ambigous and thus hard to read and understand
  • the wrong variable might unintentionally be used, leading to hard to spot bugs
  • confusion may arise when your working with your own code

bottom line: yes you can do it, but avoid it as much as possible, especially in big projects, as you probably will end up getting stabbed :P

Necrolis