C++ Student Question (Global and Local Variables)

jokohono 61 Reputation points
2022-01-30T01:31:15.89+00:00

Hi,

I am new learner of C++. Having questions with Global vairable and Local vairable.

When there are a Global variable and Local variable with the same name, how will you access the global variable?

Many Many Thanks

C++
C++
A high-level, general-purpose programming language, created as an extension of the C programming language, that has object-oriented, generic, and functional features in addition to facilities for low-level memory manipulation.
3,786 questions
{count} votes

4 answers

Sort by: Most helpful
  1. Igor Tandetnik 1,106 Reputation points
    2022-01-30T03:01:30.857+00:00

    With a qualified name. Consider:

    int x = 111;
    
    int main() {
        int x = 222;
        std::cout << x << ' ' << ::x << std::endl;
    }
    

    Prints 222 111. Demo

    0 comments No comments

  2. WayneAKing 4,921 Reputation points
    2022-01-30T06:44:00.87+00:00

    The example posted by Igor uses the scope resolution operator:

    Scope resolution operator: ::
    https://learn.microsoft.com/en-us/cpp/cpp/scope-resolution-operator?view=msvc-170

    "A scope resolution operator without a scope qualifier
    refers to the global namespace."

    • Wayne
    0 comments No comments

  3. kwikc 131 Reputation points
    2022-02-01T02:27:15.233+00:00

    (Thanks for converting to Answer. I was/am just wanting to add comments to King's typing)

    In C++ programming variable naming styles, local variable naming is casual, global variable naming is more descriptive and having "g_" prefix, they are not to necessarily have a same name. For example,

    #include <iostream>
    int g_totalAmount = 0;
    void IncreaseAmount(int amount)
    {
    g_totalAmount += amount;
    }
    int main()
    {
    IncreaseAmount(100);
    IncreaseAmount(200);
    std::cout << g_totalAmount << std::endl;
    return 0;
    }

    0 comments No comments

  4. NADIR HUSSAIN 1 Reputation point Student Ambassador
    2022-03-03T05:11:34.69+00:00

    include <stdio.h>

    // Global variable x
    int x = 50;

    int main()
    {
    // Local variable x
    int x = 10;
    {
    extern int x;
    printf("Value of global x is %d\n", x);
    }
    printf("Value of local x is %d\n", x);
    return 0;
    }

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.