using namespace std

closed account (NwvkoG1T)
Kindly tell me what does this statement

using namespace std

actually do?

i have found it on almost every program that i have seen on this site. and is deafult in any code blocks created cpp project.

what does the keyword using do?

and why is this line used in almost every program?
Everything in the C++ standard library is in the std namespace.

A namespace will allow you to #include your own, or 3rd party headers and ensure that you have no conflicts. Example, if you make your own function: sin(x) and then someone uses your header and the <cmath> header at the same time, they'll have a conflict. If you put your sin(x) in a namespace, then they can specify which version of sin(x) they want to use.

They can specify the one in cmath with std::sin(x), or they can specify your version with yourNamespace::sin(x). The 'problem' is that you need to prepend std:: to everything you use from the standard library which is verbose and can make things harder to read for beginners.

Now if you aren't using any other libraries and don't have too many functions in your own source file, then you can tell the compiler, "just take everything from std::". To do that, we use the command using namespace std;

Everything?

Does that mean that <math.h> is not in the STL?
You don't have to use std:: before those functions.
Isn't math.h the old C header?

Try <cmath> instead and see if those functions are in the std:: namespace.
Open up <cmath> and find out ;)

cmath will look something like this:

1
2
3
4
5
6
7
8
9
#include <math.h>

namespace std
{
using ::acosf; using ::asinf;
using ::atanf; using ::atan2f; using ::ceilf;
using ::cosf; using ::coshf; using ::expf;
...
}


It's effectively mapping to contents of math.h into the std namespace.

Last edited on
Open up indeed
http://llvm.org/svn/llvm-project/libcxx/trunk/include/cmath
1
2
3
4
5
6
7
8
9
10
11
12
13
14
// sin

using ::sin;
using ::sinf;

#ifndef _MSC_VER
inline _LIBCPP_INLINE_VISIBILITY float       sin(float __x) _NOEXCEPT       {return sinf(__x);}
inline _LIBCPP_INLINE_VISIBILITY long double sin(long double __x) _NOEXCEPT {return sinl(__x);}
#endif

template <class _A1>
inline _LIBCPP_INLINE_VISIBILITY
typename enable_if<is_integral<_A1>::value, double>::type
sin(_A1 __x) _NOEXCEPT {return sin((double)__x);}


In human language, this says: take C's double ::sin(double) into the std namespace, and then define all the other versions of sin() that C++ has in <cmath> (float sin(float), long double sin(long double), double sin(int), double sin(long), etc)
Topic archived. No new replies allowed.