Skip to content
Related Articles

Related Articles

Difference between cout and std::cout in C++
  • Last Updated : 01 Aug, 2020

The cout is a predefined object of ostream class, and it is used to print the data on the standard output device. Generally, when we write a program in Linux operating system for G++ compiler, it needs “std” namespace in the program.We use it by writing using namespace std; then we can access any of the objects like cout, cin.

C++




// Program to show the use of cout
// without using namespace
  
#include <iostream>
int main()
{
    std::cout << "GeeksforGeeks";
    return 0;
}
Output:
GeeksforGeeks

std:cout: A namespace is a declarative region inside which something is defined. 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.

C++




// Program to show use of using namespace
  
#include <iostream>
using namespace std;
int main()
{
    cout << "GeeksforGeeks";
    return 0;
}
Output:
GeeksforGeeks

What would happen if neither “using namespace std” nor “std::” is used for cout?



C++




// Program without using
// using namespace std and std::
  
#include <iostream>
  
int main()
{
    cout << "GeeksforGeeks";
    return 0;
}

Compilation Error:

main.cpp: In function ‘int main()’:
main.cpp:5:2: error:
  ‘cout’ was not declared in this scope
  cout<<"GeeksforGeeks"<<endl;
  
main.cpp:5:2: note: suggested alternative:
In file included from main.cpp:1:0:
/usr/include/c++/7/iostream:61:18: note:   ‘std::cout’
   extern ostream cout;  /// Linked to standard output

Difference between “using namespace std cout” and “std::cout”?

In C++, cout and std::cout both are same, but there are some basic differences are following:

S. No.coutstd::cout
1.namespace std must be used in the programWithout using namespace std, you should use std::cout.
2.cout is a predefine object of ostream classit is used to print the data as well as values
3.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
Want to learn from the best curated videos and practice problems, check out the C++ Foundation Course for Basic to Advanced C++ and C++ STL Course for foundation plus STL.  To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.
My Personal Notes arrow_drop_up
Recommended Articles
Page :