c++std

Why is "using namespace std" necessary here?


I am currently using three files: main.cpp, functions.cpp, functions.h.

The functions.h file looks like this:

#ifndef FUNCIONES_H
#define FUNCIONES_H

#include <vector>
#include <string>
#include <iostream>

// 1)
void selection_sort(vector<int> & v);
void insertion_sort(vector<int> & v);


#endif

Note that in the code there is no such line that says using namespace std, since I want to use it manually, for example, std::cout. But an error shows up in the functions declaration. This is the error message:

incomplete type "void" is not allowedC/C++(70),

identifier "vector" is undefinedC/C++(20),

type name is not allowedC/C++(254), and

identifier "v" is undefinedC/C++(20).

This seems weird to me, because I already included the vector library, but since I am not using the std library it seems like the file doesn't know what a vector is...

I could just type using namespace std and solve this problem though, but I want to know why it doesn't work like this.


Solution

  • cout and vector are both names in the standard library. All of these names are located in the std namespace and need to be prefixed accordingly when used. The only exception are preprocessing macros in the standard library, which in their nature are not bound by namespaces.

    In contrast int and void are core language keywords and not part of the standard library.

    Some names in the standard library can additionally be declared in the global namespace scope, so that no std:: prefix is necessary. For example if you try to write printf instead of std::printf that will most likely work, but the declarations in the global namespace scope do only exist for names derived from C for historical reasons and are only guaranteed to be declared if you include the corresponding C-style header (e.g. <stdio.h>). On the other hand these header forms do not guarantee the declarations in std to be available, so I suggest simply ignoring they exist unless you need C compatibility.