Results 1 to 2 of 2

Thread: Global variable and Local variable with the same name, how will you access the global

  1. #1

    Thread Starter
    New Member
    Join Date
    Nov 2020
    Location
    India
    Posts
    3

    Global variable and Local variable with the same name, how will you access the global

    If there are two variables with the same name but different scope, like 1st one is local variable and the other is a global variable, the compiler will give preference to a local variable.

    For Example.

    #include<iostream.h>
    int x= 10;
    int main()
    {
    int x= 2;
    cout<<”Global Variable x = “<<::x;
    cout<<”\nlocal Variable x= “<<x;
    }
    Output:

    Global Variable x = 10
    local Variable x= 2

  2. #2
    Super Moderator jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    110,299

    Re: Global variable and Local variable with the same name, how will you access the gl

    Is that really C# code? It looks more like C/C++.

    In C#, you're nor talking about a global variable at all but, rather, a member variable (AKA a field) and a local variable. To refer to the field specifically, you would qualify it with 'this'.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width