+ 2

Hey friends please explain me how namespace works in this below code?

#include <iostream> using namespace std; namespace alpha{int var =1;} namespace beta{ int var = alpha ::var +1; } int main() { beta::var+=alpha::var; { using namespace beta; cout<<var; } return 0; } //output is 3,

14th Sep 2018, 7:18 AM
Albert Whittaker :Shaken To Code
Albert Whittaker :Shaken To Code - avatar
2 Antworten
+ 1
Namespaces are used to group entities together and to avoid naming conflicts, especially in larger code bases. In your code, each "var" is grouped in a different namespace, thus they are different variables. Since alpha::var is equal to 1, beta::var is 1 +1 = 2. Now in main() you add alpha::var (1) to beta::var (2), resulting in beta::var becoming 3. The brackets define a local scope in main(), and in this scope, you basically tell the compiler to search inside "namespace beta" whenever it is unable to identify something by "using namespace beta;". The compiler can't find "var", so it looks inside "beta", finds "var" there, and therefore uses "beta::var" in the cout-statement. That is why the result is 3. Some helpful links: https://en.cppreference.com/w/cpp/language/namespace https://www.geeksforgeeks.org/namespace-in-c/ http://www.cplusplus.com/doc/oldtutorial/namespaces/
14th Sep 2018, 7:45 AM
Shadow
Shadow - avatar
0
your beta namespace variable named var is equal to 2 because alpha::var equals to 1 and you sum it with 1 and assigned the value to beta::var and then in main() you sum beta::var value with alpha::var which means that beta::var==2+1==3
14th Sep 2018, 8:58 PM
KarSah
KarSah - avatar