Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why std::cout instead of simply cout?

Tags:

c++

iostream

I get these error messages for all cout and endl:

main.cc:17:5: error: ‘cout’ was not declared in this scope main.cc:17:5: note: suggested alternative: /usr/include/c++/4.6/iostream:62:18: note:   ‘std::cout’ 

After following the suggestion, everything is fine. Now I am curious, why I had to do that. We used C++ in classes before, but I never had to write a std:: before any of those commands. What might be different on this system?

like image 370
erikbstack Avatar asked Jun 08 '12 13:06

erikbstack


People also ask

Why do we use std cout instead of cout?

So, in that case, cout is defined in the std namespace. Thus, std::cout states that is cout defined in the std namespace otherwise to use the definition of cout which is defined in std namespace. So, that std::cout is used to the definition of cout from std namespace.

Should I use std :: cout or cout?

cout and std::cout both are same, but the only difference is that if we use cout, namespace std must be used in the program or if you are not using std namespace then you should use std::cout.

Why do we write std :: in C++?

The string and vector which we want to use are in the C++ standard library, so they belong to the std namespace. This is why you need to add std:: to them. It is the same reason to use std:: for cout and cin .

Is printf faster than std :: cout?

As you can see, using printf and then fflush ing takes about 5 times less time than using std::cout .


2 Answers

It seems possible your class may have been using pre-standard C++. An easy way to tell, is to look at your old programs and check, do you see:

#include <iostream.h> 

or

#include <iostream> 

The former is pre-standard, and you'll be able to just say cout as opposed to std::cout without anything additional. You can get the same behavior in standard C++ by adding

using std::cout; 

or

using namespace std; 

Just one idea, anyway.

like image 53
FatalError Avatar answered Oct 22 '22 00:10

FatalError


In the C++ standard, cout is defined in the std namespace, so you need to either say std::cout or put

using namespace std; 

in your code in order to get at it.

However, this was not always the case, and in the past cout was just in the global namespace (or, later on, in both global and std). I would therefore conclude that your classes used an older C++ compiler.

like image 39
Matthew Walton Avatar answered Oct 22 '22 00:10

Matthew Walton