In: Computer Science
C++: How are std::cout << “hello world” and std::cout << “hello” << ‘ ‘ << “world” different?
code:
#include <iostream>
int main()
{
std::cout << "hello world" ;
return 0;
}
Explain:
On compiling the above code, Hello World will be printed on the screen.
Let's start with std::cout << "Hello World"; - std is a namespace and cout is defined in this std namespace.
Here , in this code the space between two words hello and world is already give by user hence space will print automatically.
Basically, a namespace is a special area inside which something is defined. So, in this case, cout is defined in std namespace.
Thus, std::cout states that cout is defined in the std namespace or to use the definition of cout which is defined in std namespace.
So, std::cout is used to use the definition of cout from std namespace.
<< is the output
operator.
here << is used to pass "Hello World" to
cout. Thus, std::cout << "Hello World";
passes "Hello World" to cout and cout will print this Hello World
on the screen.
code:
#include <iostream>
int main()
{
std::cout << "hello" << ' ' << "world" ;
return 0;
}
Explain:
In the above example, std::cout << "hello" << ' ' << "world" ; printed "Hello world" .
Thus, the space between two words hello and world given by user by using <<' ' that's why they seperated from each otherwise user not give space it will print like Helloworld i, e no space will be there .
std::cout << “hello world” | The space is already given in program itself hence the output is Hello world the space is give already between two words hello and world |
std::cout << “hello” << ‘ ‘ << “world” |
The space is given using << ' ' if the space will not provide using using <<' ' the words will not seperate and print like Helloword But because space is given it print output like Hello world |