C++ Student Question (Global and Local Variables)

jokohono 61 Reputation points


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

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.
2,747 questions
{count} votes

4 answers

Sort by: Most helpful
  1. Igor Tandetnik 1,101 Reputation points

    With a qualified name. Consider:

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

    Prints 222 111. Demo

  2. WayneAKing 4,256 Reputation points

    The example posted by Igor uses the scope resolution operator:

    Scope resolution operator: ::

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

    • Wayne
  3. Kwik C 106 Reputation points

    (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()
    std::cout << g_totalAmount << std::endl;
    return 0;

  4. NADIR HUSSAIN 1 Reputation point

    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;