1
int x = 1;
if (x > 0)
    int x = 2;
cout << x;

I expected the output would to be 2 because the condition is true, but what happens here?

I received 1 as output.

πάντα ῥεῖ
  • 1
  • 13
  • 116
  • 190
Mo'men
  • 37
  • 1
  • 7
    The `x` under the `if` is a different variable than the one above it. Remove the type qualifier from it. Just use `x = 2;`. – R Sahu Jul 26 '18 at 18:38

2 Answers2

10

You've shadowed the variable. This occurs when a variable declared within one scope has the same name as a variable declared in an outer scope.

Making this modification will give the output you expect:

int x = 1;
if (x > 0) {
  x = 2; // now you're modifying the same x
}
cout << x;
Alex Johnson
  • 958
  • 8
  • 23
4

In c++ variable or other symbol declarations are local to their scope, redeclaring them in a different scope is called shadowing, and you will see no effect of the assignment outside of your current scope level. This concerns

  • Local scope (everything within braces {} or immediately appearing after a control flow statement like if, else, case, while or for)
    Typical examples:

    int i = 5;
    if(i == 5)
        int i = 2; // Single statement scope following the if
                   // Changes the local variable's value
    

    int j = 42;
    if(j == 42) {
        int j = 2; // Scoped block local variable
                   // Changes the local variable's value
    }
    
  • Class scope (any class member variables)
    Typical examples:

    class MyClass {
        int myMember_;
    public:
        MyClass(int aValue) {
            int myMember_; // another local variable in the constructor function
            myMember_ = aValue; // Changes the local variable's value
        }
    };
    

    class MyClass {
        int myMember_;
    public:
        MyClass(int aValue) {
            int myMember_ = aValue; // Changes the local variable's value
        }
    };
    
  • Namespace scope (any namespace global variables).
    Same principle as above. Namespaces can shadow variables (symbols) from other namespaces


Your c++ compiler should probably give you a warning about the appearance of one of the above mentioned situations.
With specifically GCC (g++) you can force that using the -Wshadow compiler flag.

πάντα ῥεῖ
  • 1
  • 13
  • 116
  • 190