sc0rp10n.my7h
sc0rp10n.my7h

Reputation: 341

Declaring a variable as global and then as local -Shadowing-

What does it mean to declare a variable as global and then re-declare it as local like this:

int a = 0;
int main()
{
    int a = 7;
    return 0;
}

I saw this example in a reference, but I don't understand it. please put into consideration that I'm a beginner at programming with C++

Upvotes: 3

Views: 107

Answers (2)

ItsTheJourney
ItsTheJourney

Reputation: 23

You need to understand Scope of a variable. A variable defined within a method/curly braces is valid as long as you are referencing it within that curly braces. That said, in your code, to access the local "a", you use it directly & to use the global "a" (defined outside main()), prefix with the scope resolution operator (::a)

But, avoid a scenario like this. Give unique names.

Upvotes: 1

Suren Srapyan
Suren Srapyan

Reputation: 68665

This means that in your main method if you use only a, you will refer to that one which is declared in that method, because it shadows the global one. To access the global one within main, you need to access via ::a. Within other methods if you will use a, you will refer to that one which is global for every method in that file. Scopes work like this, if it doesn't find a variable, it goes and tries to find in the outer scope and so on to the global scope.

One advice avoid from global variables

Upvotes: 4

Related Questions