Open In App

Difference between cout and std::cout in C++

Improve
Improve
Like Article
Like
Save
Share
Report

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. cout std::cout
1. A “namespace std” must be written into the program “std::cout” must be used, if “namespace std” was not declared previously
2. cout is a predefined object of the ostream class “std::cout” calls the Standard Template/Iostream Library, since “cout” is only defined in the “std” namespace
3.

Declaring the namespace before hand gives access to many functions

such as cin, cout etc.

This is just an implicit initialization of the std library performed inside the function, i.e alongwith 

the main computation 



Last Updated : 08 Nov, 2022
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads