Thread: I have no idea what's going on

  1. #16
    Registered User
    Join Date
    Oct 2006
    Posts
    3,445
    what everyone seems to be failing to realize is that even when a "using namespace std" declaration is employed in the global scope, a member of a child scope may still be called by any of the names defined in the global scope. child scope names have precedence over parent scope names. take the following code for example:

    Code:
    #include <iostream>
    #include <string>
    
    using namespace std;
    
    int main(void)
    {
    	char* string = nullptr;
    	return 0;
    }
    the variable called "string" in main() does not conflict with std::string, because the C++ compiler takes any unqualified identifier to mean the one defined in the nearest scope.

    even the following code is valid:

    Code:
    #include <iostream>
    #include <string>
    
    using namespace std;
    
    int main(void)
    {
    	typedef char* string;
    	string s = nullptr;
    	return 0;
    }
    I have confirmed this behavior on both G++ 4.5.1 and VC++ 2010.

  2. #17
    Registered User
    Join Date
    Apr 2006
    Posts
    2,149
    That's true even if using namespace std is in the child scope.

    And who's "everybody"? your example is virtually identical to the one I linked to.

    For more confusion, try this:
    Code:
    #include <string>
    #include <iostream>
    int main()
    {
       using namespace std;
       string string;
       string = "hello\n";
       cout << string;
    }
    Last edited by King Mir; 07-18-2011 at 08:04 PM.
    It is too clear and so it is hard to see.
    A dunce once searched for fire with a lighted lantern.
    Had he known what fire was,
    He could have cooked his rice much sooner.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Any idea?
    By Moony in forum C Programming
    Replies: 9
    Last Post: 07-05-2006, 02:47 AM
  2. Got idea but is this possible?
    By Hugo716 in forum Game Programming
    Replies: 10
    Last Post: 06-06-2006, 05:41 AM
  3. Have no idea (please help)
    By HAssan in forum C Programming
    Replies: 5
    Last Post: 01-25-2006, 02:16 PM
  4. IDEA: Tic-Tac-Toe
    By ygfperson in forum Contests Board
    Replies: 2
    Last Post: 09-02-2002, 05:25 PM
  5. Good idea, bad idea.
    By sean in forum A Brief History of Cprogramming.com
    Replies: 2
    Last Post: 06-15-2002, 12:26 PM