Identifier scopes, I have trouble understanding this rule.

0 Bob huginstien · April 20, 2015
5. "An identifier's scope does not include any nested block that contains a locally declared identifier with the same name (i.e. local identifiers have name precedence)"

if there  were  multiple Identifiers with the same local name, would it only choose one of them preferably in the first block and ignore the rest of those identifiers with the same name? Also would that cause an error if something like this were to happen ? Thank you in advance.

Post a Reply

Replies

Oldest  Newest  Rating
+1 K D · April 20, 2015
this Program should i hope explain...
#include 

using namespace std;
int i = 3489; // this i lives as long
// as the program
void output(){
cout
so the blocks local variable takes precedence.
+1 K D · April 20, 2015
Bleh didn't work.  The local block Always takes precedence.

#include <iostream>

using namespace std;
int i = 3489; // this i lives as long
                    // as the program
void output(){
    cout << "Global i after for loop = " << i << endl;
}
int main(){
    cout << "Global i before for loop = " << i << endl;
    int i = 56; // this i lives as long
    // as the main
    cout << "\tMain's i before for loop = " << i << endl;
    for (int i = 0; i < 10;i++){     // this i lives as long
                                               // as the for loop
        cout << "\t\ti in for loop = " << i << endl;
    }
    cout << "\tMain's i after for loop = " << i << endl;

    // This will print out 56 because of the fact that
    // main has a local variable called i
    cout << "Global i after for loop = " << i << endl;

    // I must use the function to access the global i because
    // there is a local variable called i and local ALWAYS takes
    // precedence.
    output();

    return 0;
}
0 Bob huginstien · April 21, 2015
Thank you K.D. for all your help!
0 K D · April 21, 2015
glad to help.
  • 1

C++

107,093 followers
About

Used in many types of software including music players, video games, and many large scale applications.

Links
Moderators
Bucky Roberts Administrator