DEV Community

Cover image for The most basic C++ program.
Araiz Naqvi
Araiz Naqvi

Posted on

The most basic C++ program.

The most basic C++ program is:

#include<iostream>
using namespace std;

int main(){
cout << "Hello kaisa hai be?";
return 0;
}
Enter fullscreen mode Exit fullscreen mode


We'll get to the headers later.
Let's first check out:

int main()


The main function is the entry point or the starting point that gcc will look for.
This is where the code execution always starts.

Now, this function can't be called anything else and has to be called main().
Also, it is mandatory for the main() to return an integer datatype.

cout << "Hello"


The cout is an object from the iostream header that is allows you to provide output.
It is followed by the insertion operator <<.

Say:

cout << "Hello";
Enter fullscreen mode Exit fullscreen mode


We are feeding Hello string into cout output stream.
The ; represents the end of a line.

return 0;


In the int main(), since the main function expects an integer to be returned we return 0.
Here, usually 0 means a successful run and any other integer means some error was hit.

If nothing is returned it is automatically assumed as return 0.

Although there is no hardstop even if you return something else, but in real life it can linked program to program to denote a certain error like say payment gateway error or whatever for example.

include iostream & namespace std


(This took me 2 hours to understand so whenever you're revising it will only take 2 mins but it toom me 2 hrs!!)


The iostream is a header that contains declarations of input and output objects.
This is included into the program using #include command which is the preprocessor directive that includes a header into the program while preprocessing for references and is done as:

#include<iostream>
Enter fullscreen mode Exit fullscreen mode


Now this header has a namespace called std which includes the declarations and usages of objects like cout, cin, endl, etc.

So whenever, we use these objects we need to call them as:

std::cout << //whatever here
Enter fullscreen mode Exit fullscreen mode


It can be imagined as:

iostream{
    std{
        cout
        cin
        endl
        ...
    }
}
Enter fullscreen mode Exit fullscreen mode


Now, iostream does not contain the actual implementation, its just the declarations and input needed by that object here. When being used its implementation is called in by the C++ standard library.

We don't need the command using namespace std, we just use it for convenience. Additionally, its recommended not to use this command.

Top comments (0)