C C++ Java Data Structure Python JavaScript CSS Ajax PL/SQL PHP Puzzles C programs C++ programs Java programs

Home » C++ programming language

What is the difference between cout and std::cout in c++?

Learn: What is the difference between cout and std::cout, how to use cout's different forms? How can we use cout with and without using 'std::'?

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.

What is cout?

cout is a predefine object of ostream class, and it is used to print the data (message as well as values) on the standard output device.

Usages of cout with and without std

Generally, when we write program in Linux operating system for GCC compiler, it needs 'std' namespace in the program.

We use it by writing using namespace std; then we can access any of the object like cout, cin without using std, but if we do not use using namespace std; then we should use std::cout etc to prevent errors.

We can encapsulate multiple classes into single namespace. Here, std is a namespace and :: (Scope Resolution Operator) is used to access member of namespace. And we include namespace std in our C++ program so that there is no need to put std:: explicitly into program to use cout and other related things.

1) Program with "using namespace std" – Error free

#include <iostream>
using namespace std;

int main()
{
	cout<<"Hi there, how are you?"<<endl;
	return 0;
}

Output

Hi there, how are you? 

2) Program without using "using namespace std" and "std::" – Error will be occurred

#include <iostream>

int main()
{
	cout<<"Hi there, how are you?"<<endl;
	return 0;
}

Output

  cout<<"Hi there, how are you?"<<endl; 
  ^ 
main.cpp:6:2: note: suggested alternative:    
In file included from main.cpp:1:0:     
/usr/include/c++/4.8.2/iostream:61:18: note:   'std::cout'
   extern ostream cout;  /// Linked to standard output    
^   
main.cpp:6:34: error: 'endl' was not declared in this scope     
  cout<<"Hi there, how are you?"<<endl; 
    ^     
main.cpp:6:34: note: suggested alternative:   
In file included from /usr/include/c++/4.8.2/iostream:39:0,     
     from main.cpp:1: 
/usr/include/c++/4.8.2/ostream:564:5: note:   'std::endl' 
     endl(basic_ostream<_CharT, _Traits>& __os)

3) Program without using "using namespace std" and using "std::" – Error free

#include <iostream>

int main()
{
	std::cout<<"Hi there, how are you?"<<std::endl;
	return 0;
}

Output

Hi there, how are you? 

Here, std:: will be used with cout and endl.









COMMENTS