C++ Cosine works without the std namespace - Why? [duplicate] - c++

This question already has answers here:
Why are some functions in <cmath> not in the std namespace?
(3 answers)
Closed 9 years ago.
I have a fairly large application and I am working without the std namespace, I noticed I wasn't including std::cos or std::sin yet I am getting the right results. Why?
An example of some cut down code would be:
#include <ctime>
#include <cmath>
#include <iostream>
#include <vector>
//#include <unistd.h>
#include <fstream>
#include <sstream>
#include <iomanip>
using std::cout;
using std::endl;
int main()
{
double pi = 4*(atan(1));
cout << "pi = " << pi << endl
<< "cos(pi) = " << cos(pi) << endl
<< "sin(pi) = " << sin(pi) << endl;
return 0;
}
I have left all the headers in, I am using them all in the main code. The output returns ~3.14, -1 and 1e-16 as expected. Why does this work? cos and sin are in std aren't they?
I'm using the g++ compiler on a remote unix server
Thanks

When you include <cmath>, all of the functions are declared in
std::. For the C headers, there is also a special rule, which
allows (but doesn't require) the implementation to make them
visible in the global namespace; this is because most
implementations will simply adapt the C headers, something like:
#include <math.h>
namespace std
{
using ::sin;
using ::cos;
// ...
}
This is an obvious way of implementing the library without
having to rewrite everything, just to have it in C++, and it
will result in all of the names also being present in the global
namespace.
Formally, this is a C++11 feature; pre-C++11 required that
<cmath> only introduce the symbols into std::. Practically,
all, or at least most implementations did something like the
above, and did introduce them, illegally, into the global
namespace, so C++11 changed the standard to reflect reality.

Unfortunately, library implementations are allowed to dump names from the C library into the global namespace as well as std, and many do. Even worse, in some cases only some overloads are available in the global namespace, leading to unexpected loss of precision if you don't specify the std version.
You should always use the std versions, but sadly there's no reliable way to enforce that, so you'll just have to tread carefully through this particular minefield.

Related

C++ compilling errors when using Quadprog++ with Eigen together

this is my first question here, I've searched it all over for a long time yet no solution.
I'm using QUadprog++ to solve a quadratic problem. When I use it in a test alone, it was alright. But when I implement it into my project, which contains Eigen, the Eigen operations will have errors like "Matrix A has no member named ‘lu_inverse’". If I comment the header files of Quadprog++ (Array.hh and Quadprog++.hh) out, the errors just disappear. So I assume that it was a conflict error between the header files of Eigen and Quadprog++. Does anyone have some clue? Thanks in advance!
You can also switch to one of QuadProgpp versions which can work with Eigen types directly: https://github.com/asherikov/QuadProgpp, https://www.cs.cmu.edu/~bstephe1/eiquadprog.hpp; or try an alternative implementation of the same algorithm (also Eigen based) https://github.com/asherikov/qpmad.
if your using namespace quadprogpp; then dont. your different libraries have the same typenames and thats causing the errors you have. It may be a few more characters to type quadprogpp::someFunction(); but its worth it. This is also why you shouldn't ever put a using namespace in a header ever. Its because you pollute all files that include that header with the namespace symbols and name conflicts can ensue which is the same kind of error your having right now.
the Quadprog library is in it's own namespace.
#if !defined(_ARRAY_HH)
#define _ARRAY_HH
#include <set>
#include <stdexcept>
#include <iostream>
#include <iomanip>
#include <cmath>
#include <cstdlib>
namespace quadprogpp {
enum MType { DIAG };
template <typename T>
class Vector
notice how just after the #includes there is a decleration of namespace quadprogpp{} and everything that is defined in its enclosing brackets will be defined in scope to quadprogpp, so to use any of this library you have to prefix eveything with the namespace name. this is no different than using things from the standard library. I'm quite sure you've written the standard c++ hello world
#include<iostream>
int main()
{
std::cout << "hello world!" << std::endl;
return 0;
}
cout and endl being part of namespace std have to be prefixed with std:: to access them. Many new programmers to c++ dislike this and one of the very first things they google is how to not have to type out namespaces.
#include<iostream>
using namespace std;
int main()
{
cout << "hello world" << endl;
return 0;
}
the next thing new programmers often do is learn to place their definitions in header files and their program logic in cpp files. Thats when they commit the next common mistake.
#ifndef MYHEADER
#define MYHEADER
#include<string>
#include<vector>
#include<iostream>
using namespace std; //Never do this in a header.
doing that pollutes all of your code with everything in the standard library. That may seem like a trivial thing but when you start using another library or perhaps you create your own type that has the same name as things in the standard library that causes name collisions.
That's when the compiler simply cant reason about which Vector you want. But both Quadprog.hh and Array.hh in Quadprog++ are wrapped in namespace quadprogpp to specifically prevent name collision, which is the whole purpose of namespaces. So there is somewhere in your code, likely a header file, where you've made the statement of using namespace quadprogpp;, or some other namespace that defines an Array type, and the compiler can't deduce which type your referring to in your code.
Other than removing your using namespace statements you can also prefix a typename with its namespace qualifer to disambiguate which type your talking about. In your case I'm confident your Array should be declared as quadprogpp::Array arraynamme; rather than simply Array arrayname;

Why should we use "#include<iostream>" while we are using "using namespace std"? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
I have searched this question in Google. I found some related question in stackoverflow.com and quora.com but i am still not clear about this two topics. Everyone says that we use #include<iostream> for input/output operation. Now, we take input using cin and print output using cout that means this two should be defined in #include<iostream>. But without using using namespace stdwe still can't take any input nor can print something on console. So, my questions are-
Where is cin and cout actually declared and defined? Is it in #include<iostream>or in namespace std?
If in #include<iostream>why should we use using namespace std?
If in namespace std why should we use #include<iostream?
After reading some article on the web and watching some videos on YouTube, I'm assuming cout and cin is defined in namespace std and the namespace std doesn't make any sense alone because it is defined in #include<iostream>. That's why we need to use them both. (Just my thought let me know if I am right or not.)
The purpose of this question is to be clear about this two facts. If you can help it would be great.
cin and cout are defined in the header iostream and in the namespace std. These concepts are orthogonal. iostream is a file name and std is a namespace used by the source code of that file.
As a way of keeping things organized, c++ provides namespaces. All of the standard library is defined within the namespace called std. Other libraries you might write or include may use their own namespace. For example, you might include a physics library in your project which wants to define the concept of algebraic vectors. By using it's own namespace (let's called if physlib) it can differentiate between it's vector (physlib::vector) and the standard vector (std::vector). Namespaces can also be nested to help organize large projects. For example, time keeping parts of the standard library are in std::chrono and file system related components are in std::filesystem.
The preferred way of using cin and cout is as following. :
#include <iostream>
int main()
{
std::cout << "Hello, World!\n";
return 0;
}
The statement using namespace std is simply an instruction to look in the namespace std by default. It allows you to omit the std:: part of using standard library components. It's generally regarded as a bad idea to used using namespace std.
Why should we use #include <iostream>
To bring the standard library's I/O functionality into our program.
while we are using using namespace std?
This allows us to use that functionality without writing std:: each time we do.
This is unrelated to the previous step. Writing only using namespace std does not bring I/O functionality into your program, and writing only #include <iostream> does not allow us to use that functionality without writing its components' names out in full (including the std:: prefix).
The #include directive determines what we can use;
The using namespace declaration determines how we can use it.
Perfectly fine:
#include <iostream>
int main()
{
std::cout << "Hello world!\n";
}
Also valid:
#include <iostream>
using namespace std;
int main()
{
cout << "Hello world!\n";
}
Not valid:
int main()
{
std::cout << "Hello world!\n";
}
And neither is this:
using namespace std;
int main()
{
std::cout << "Hello world!\n";
}
or this:
using namespace std;
int main()
{
cout << "Hello world!\n";
}
#include <iostrem> tells the compiler to pull in the contents of the header iostream. That header provides, among other things, declarations of the objects std::cin and std::cout. So the basic "Hello, world" program looks like this:
#include <iostream>
int main() {
std::cout << "Hello, world\n";
return 0;
}
Similarly, if you want to use std::vector, you tell the compiler about it with #include <vector>. Same thing for the rest of the standard library: whatever it is that you want to use, find out which header declares it and #include that header.
using namespace std; doesn't define any names for you. It tells the compiler to pretend that any names that have been defined in the namespace std are also defined in the scope where using namespace std; occurs. So that means that instead of writing std::cout you can write cout, and the compiler will figure out that you meant std::cout. Unless, of course, you've written something yourself with the name cout (or any other name that's in std and declared in a header that you've #included), in which case that using declaration makes the use of the name ambiguous. There is no good reason to write using namespace std;. Just use the right names for things: std::cout is clear and unambiguous.
Where is cin and cout actually declared and defined? Is it in #include<iostream> or in namespace std?
It's not or. cin and cout are declared in the iostream header file within the namespace std.
If in #include< iostream> why should we use using namespace std?
You shouldn't. Either fully qualify the global variables like std::cin or std::cout. There's a number of reasons why you shouldn't use using namespace std; (at least in header files).
If in namespace std why should we use #include<iostream>?
Because you need the declarations to compile your code.
iostream is part of the standard library, here is what the "iostream.h" file would look like if you were to implement it yourself:
namespace std{
// code about cin
extern ostream cin;
// code about cout
extern ostream cout;
}
(see c++ STL cout source code)
Where is cin and cout actually declared and defined? Is it in #include <iostream> or in namespace std?
So cin/cout are declared and define in the standard library under the
namespace std. This means that if you want to use it in your code you can do :
int main()
{
std::cout << "Hello";
}
If in #include<iostream> why should we use using namespace std?
You don't need using namespace std, you could call std::cout everywhere instead of cout, but you can see how this can make your code verbose and annoying to type.
using namespace std in your whole file is actually discouraged as it could have unintended effect, usually you could use only
using std::cout;
using std::cin;
where needed.
The reason the using is needed (or the need for explicitly writing std:cout , is imagine you have the following code:
#include <iostream>
namespace mycoolnamespace
{
class foo {
public:
foo& operator<< (const std::string& echo)
{
// do stuff
}
};
foo cout; // created a variable called cout
}
int main()
{
cout << "Hello";
// ^^^^ compiler can't know if you meant to use std::cout or mycoolnamespace::cout here!
// Potential fix:
std::cout << "Hello"
}
If in namespace std why should we use #include<iostream>?
By default not all function/classes from the standard library are included in your program, otherwise a simple "Hello world" program would give a lot of work to the compiler since it would need to parse all the existing classes/functions in the entire standard library. #include<iostream> tells the compiler that you need the functions/classes available in the standard library's iostream 'file'

No need for std namespace when using isalpha function

I am a beginner in C++. From what I understand, in order to use a name, we have to include the library that consist of that name. Thereafter, we can either prepend the name of the namespace or use the using keyword.
E.g.
Without using keyword:
std::cout << "Hello Word!" << std::endl;
With using keyword:
using namespace std;
cout << "Hello World!" << endl;
I saw a working code sample online that uses the isalpha name from the locale library in the std namespace. However, that sample does not use any of the methods mentioned above.
E.g.
#include <iostream>
#include <locale>
int main() {
std::cout << isalpha('a') << std::endl;
}
Could someone please explain to me why the code still works?
When you include a C++ header for a C library facility, that is, a header <cfoo> corresponding to a C header <foo.h>, then the names from the C library are declared in namespace std. However, additionally it is unspecified whether the names are also declared in the global namespace.
In your case it seems that they are. But you cannot rely on that, nor should you.
There are two correct variants, as follows:
// C++ header
#include <cctype>
int main()
{
return !std::isalpha('a');
}
// C header
#include <ctype.h>
int main()
{
return !isalpha('a');
}
A compiler is permitted to declare extra names beyond those specified by the Standard, but your code is not portable if it relies on such artefacts of the implementation.
Always include the correct headers for the functions you use, and you will avoid surprises.

namespace usage

I'm trying to start using namespaces the correct (or at least best) way.
The first thing I tried to do was to avoid putting using namespace xxx; at the beginning of my files. Instead, I want to using xxx::yyy as locally as possible.
Here is a small program illustrating this :
#include <iostream>
#include <cstdlib>
#include <ctime>
int main() {
using std::cout;
using std::endl;
srand(time(0));
for(int i=0; i<10;++i)
cout << rand() % 100 << endl;
return 0;
}
If I omit the lines using std::cout; or using std::endl, the compiler will complain when I'm trying to use cout or endl.
But why is this not needed for srand, rand and time ? I'm pretty sure they are in std, because if I try to specifically pour std:: in front of them, my code is working fine.
If you use cstdlib et al. the names in them are placed in both the global and the std:: namespaces, so you can choose to prefix them with std:: or not. This is seen as a feature by some, and as a misfeature by others.
If you really want to know, take a close look at the ctime and cstdlib headers. They were built backwards-compatible.
Note: all this using vs. using namespace business is about readability. If your IDE would allow to just not show the namespaces when you don't want to see them, you wouldn't need these constructs...
I prefer to omit using and just have the std::cout every time just to maintain readability. although this is probably only useful in larger projects
As long as we on the subject, there's also a thing called Koenig Lookup which allows you to omit a namespace identifier before a function name if the arguments it take come from the same namespace.
For example
#include <iostream>
#include <algorithm>
#include <vector>
void f(int i){std::cout << i << " ";}
int main(int argc, char** argv)
{
std::vector<int> t;
// for_each is in the std namespace but there's no *std::* before *for_each*
for_each(t.begin(), t.end(), f);
return 0;
}
Well, it's not related directly but I though it may be useful.

What requires me to declare "using namespace std;"?

This question may be a duplicate, but I can't find a good answer. Short and simple, what requires me to declare
using namespace std;
in C++ programs?
Since the C++ standard has been accepted, practically all of the standard library is inside the std namespace. So if you don't want to qualify all standard library calls with std::, you need to add the using directive.
However,
using namespace std;
is considered a bad practice because you are practically importing the whole standard namespace, thus opening up a lot of possibilities for name clashes. It is better to import only the stuff you are actually using in your code, like
using std::string;
Nothing does, it's a shorthand to avoid prefixing everything in that namespace with std::
Technically, you might be required to use using (for whole namespaces or individual names) to be able to use Argument Dependent Lookup.
Consider the two following functions that use swap().
#include <iostream>
#include <algorithm>
namespace zzz
{
struct X {};
void swap(zzz::X&, zzz::X&)
{
std::cout << "Swapping X\n";
}
}
template <class T>
void dumb_swap(T& a, T& b)
{
std::cout << "dumb_swap\n";
std::swap(a, b);
}
template <class T>
void smart_swap(T& a, T& b)
{
std::cout << "smart_swap\n";
using std::swap;
swap(a, b);
}
int main()
{
zzz::X a, b;
dumb_swap(a, b);
smart_swap(a, b);
int i, j;
dumb_swap(i, j);
smart_swap(i, j);
}
dumb_swap always calls std::swap - even though we'd rather prefer using zzz::swap for zzz::X objects.
smart_swap makes std::swap visible as a fall-back choice (e.g when called with ints), but since it doesn't fully qualify the name, zzz::swap will be used through ADL for zzz::X.
Subjectively, what forces me to use using namespace std; is writing code that uses all kinds of standard function objects, etc.
//copy numbers larger than 1 from stdin to stdout
remove_copy_if(
std::istream_iterator<int>(std::cin), std::istream_iterator<int>(),
std::ostream_iterator<int>(std::cout, "\n"),
std::bind2nd(std::less_equal<int>(), 0)
);
IMO, in code like this std:: just makes for line noise.
I wouldn't find using namespace std; a heinous crime in such cases, if it is used in the implementation file (but it can be even restricted to function scope, as in the swap example).
Definitely don't put the using statement in the header files. The reason is that this pollutes the namespace for other headers, which might be included after the offending one, potentially leading to errors in other headers which might not be under your control. (It also adds the surprise factor: people including the file might not be expecting all kinds of names to be visible.)
The ability to refer to members in the std namespace without the need to refer to std::member explicitly. For example:
#include <iostream>
using namespace std;
...
cout << "Hi" << endl;
vs.
#include <iostream>
...
std::cout << "Hi" << std::endl;
You should definitely not say:
using namespace std;
in your C++ headers, because that beats the whole point of using namespaces (doing that would constitute "namespace pollution"). Some useful resources on this topic are the following:
1) stackoverflow thread on Standard convention for using “std”
2) an article by Herb Sutter on Migrating to Namespaces
3) FAQ 27.5 from Marshall Cline's C++ Faq lite.
First of all, this is not required in C - C does not have namespaces. In C++, anything in the std namespace which includes most of the standard library. If you don't do this you have to access the members of the namespace explicitly like so:
std::cout << "I am accessing stdout" << std::endl;
Firstly, the using directive is never required in C since C does not support namespaces at all.
The using directive is never actually required in C++ since any of the items found in the namespace can be accessed directly by prefixing them with std:: instead. So, for example:
using namespace std;
string myString;
is equivalent to:
std::string myString;
Whether or not you choose to use it is a matter of preference, but exposing the entire std namespace to save a few keystrokes is generally considered bad form. An alternative method which only exposes particular items in the namespace is as follows:
using std::string;
string myString;
This allows you to expose only the items in the std namespace that you particularly need, without the risk of unintentionally exposing something you didn't intend to.
Namespaces are a way of wrapping code to avoid confusion and names from conflicting. For example:
File common1.h:
namespace intutils
{
int addNumbers(int a, int b)
{
return a + b;
}
}
Usage file:
#include "common1.h"
int main()
{
int five = 0;
five = addNumbers(2, 3); // Will fail to compile since the function is in a different namespace.
five = intutils::addNumbers(2, 3); // Will compile since you have made explicit which namespace the function is contained within.
using namespace intutils;
five = addNumbers(2, 3); // Will compile because the previous line tells the compiler that if in doubt it should check the "intutils" namespace.
}
So, when you write using namespace std all you are doing is telling the compiler that if in doubt it should look in the std namespace for functions, etc., which it can't find definitions for. This is commonly used in example (and production) code simply because it makes typing common functions, etc. like cout is quicker than having to fully qualify each one as std::cout.
You never have to declare using namespace std; using it is is bad practice and you should use std:: if you don't want to type std:: always you could do something like this in some cases:
using std::cout;
By using std:: you can also tell which part of your program uses the standard library and which doesn't. Which is even more important that there might be conflicts with other functions which get included.
Rgds
Layne
All the files in the C++ standard library declare all of its entities within the std namespace.
e.g: To use cin,cout defined in iostream
Alternatives:
using std::cout;
using std::endl;
cout << "Hello" << endl;
std::cout << "Hello" << std::endl;
Nothing requires you to do -- unless you are implementer of C++ Standard Library and you want to avoid code duplication when declaring header files in both "new" and "old" style:
// cstdio
namespace std
{
// ...
int printf(const char* ...);
// ...
}
.
// stdio.h
#include <cstdio>
using namespace std;
Well, of course example is somewhat contrived (you could equally well use plain <stdio.h> and put it all in std in <cstdio>), but Bjarne Stroustrup shows this example in his The C++ Programming Language.
It's used whenever you're using something that is declared within a namespace. The C++ standard library is declared within the namespace std. Therefore you have to do
using namespace std;
unless you want to specify the namespace when calling functions within another namespace, like so:
std::cout << "cout is declared within the namespace std";
You can read more about it at http://www.cplusplus.com/doc/tutorial/namespaces/.