Skip to content

Understanding our basic C++ program (1)

Course: C++ Part 1 - chapter 2

#include<iostream>
using namespace stdl
int main() {
cout<<"Hello World"<<endl;
return 0;
}

Let’s understand it part by part

  1. #include<iostream> : This is how we import libraries in C++. Consider it same as import axios from "axios". The general structure is #include<library_name> . iostream is a library that imports the I/O objects.
  2. using namespace std; : In C++, a namespace is a collection of related names or identifiers (functions, class, variables) which helps to separate these identifiers from similar identifiers in other namespaces or the global namespace. Almost everytime, we will be using the std namespace only, so don’t worry about this a lot.
  3. int main(): main function is the entry point for a file / program. int is the return type of the main method. Generally we will return 0 to indicate successful completion. We can also return error codes to indicate what kind of error occurred. However, in our case we will only return 0.
  4. cout: Used for printing the output to the terminal (or some file). Similar to console.log() in Javascript
  5. endl: Prints a new line after the output is printed. In C++, we need to manually specify newlines using endl or \n. For example:
cout<<"Hello ";
cout<<"World";
Output: Hello World
  1. return 0: It returns 0 from the main function.

An obvious question comes to our mind, what are the different libraries we need to import? We can import different libraries separately for getting different functionalities and data structures. For example, iostream for I/O operations, stack for Stacks, vector for vectors (dynamic arrays).

However, don’t worry! You don’t need to import all of them. There is a special library called bits/stdc++.h that includes all these common libraries. You will in 99% of the cases (if not 100), not need to import anything else. Import it using:

#include<bits/stdc++.h>

💡 bits/stdc++ library is distributed with GCC. So incase, you see error like bits/stdc++.h is not found, install GCC (in case of Mac you can use brew install gcc)