user4173586
user4173586

Reputation:

Printing a wrong value

Below is the program where out of the block when we want to print the value of x, then still it is giving 200, but it should be come out 100. What am I doing wrong?

#include<iostream>

using namespace std;

int x = 50;                //global x

int main ()
{
int x = 100;          //x redeclared local to main

{
    int inn = x;
    x = 200;         //x declared again in inner block

    cout << " This is inner block " << endl;
    cout << " inn = " << inn << endl;
    cout << " x = " << x << endl;
    cout << " ::x = " << :: x << endl;
}   

cout << endl << " This is outer block " << endl;
//value of x should be 100 ,but it is giving 200
cout << " x = " << x << endl;   
cout << " ::x = " << :: x << endl;
return 0;
}    

Upvotes: 0

Views: 72

Answers (1)

x = 200;         //x declared again in inner block

No, that is not declaring x. If you had written:

int x = 200;

That would have been a declaration, and given you the result you perhaps expected. And although it's possible to access the global scoped x with ::x anywhere in the program, if you actually declared another x in the innermost block then code in that block couldn't get at the outer x of main (at least not directly):

how to access a specific scope in c++?

But as written, it is just an assignment in the innermost block that scopes to the x in main. Not a declaration.

Upvotes: 6

Related Questions