Why didn't the value of x change when the condition is true?

  • A+
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.


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; 


:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: