Why the output of the following code is not 41? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 2

Why the output of the following code is not 41?

why using namespace does not forces nm::x to be used? https://code.sololearn.com/cEN8GyC6UP27/?ref=app

7th Feb 2019, 3:35 PM
Vedansh
Vedansh - avatar
6 Answers
+ 2
The variable x defined in the main function hides the name defined in the namespace N. As guidence, a name may be hidden by inner scope defined by a namespace. If you want to refer to the variable in the N namespace you should use the scope resolution operator like so: N::x. Also, if the variable was defined in a global scope you could refer to it like so: ::x. As a side note: This is the main reason why the use of using namespace YOURNAMESPACE is considered bad practice as it can lead to unexpected behaviors.
7th Feb 2019, 4:22 PM
Jhon
Jhon - avatar
+ 5
You need std::cout<<nm::x; to output 1. A local variable seems to take precedence over a variable of the same name in a name space that is being used.
9th Feb 2019, 12:31 PM
Sonic
Sonic - avatar
+ 2
Another solution would be to limit the scope of the variable defined in main like shown here. https://code.sololearn.com/csWUHqqTKrD3/?ref=app
7th Feb 2019, 4:30 PM
Jhon
Jhon - avatar
0
The output of 44 only not 41 vedansh Mittal
8th Feb 2019, 12:11 PM
Oviya arumugam
Oviya arumugam - avatar
- 3
Llwlwpa ap P20wlp S
8th Feb 2019, 4:20 AM
TAUHID ALAM
TAUHID ALAM - avatar