Breakdown of a Simple C++ program step by step

https://www.youtube.com/watch?v=MyM2PnhVgg4&feature=youtu.be

When you first start to learn a programming language, you are most likely going to start with displaying “Hello World” in the output of the program. Most other resources show the code but they don’t break down step by step of why we need each component for the program to run. With the source code below, let’s look at breaking down this simple C++ program and understand why we need each component.

breaking down simple C++ program

output of simple C++ program

Line 1: // My first C++ Program
Two slash signs show that it is a comment inserted by the programmer. They do not affect the code because they are ignored by the complier. Comments are important in because programmers use them to explain what is happening in the code or observations. Another way to comment code is by code blocks with:

/*
This is my first C++ program
*/

Line 2: #include
Lines starting with a hash tag sign (#) indicate that we are including what we call a header file. Without this, we cannot perform standard input and output operations, such as writing the output of “This is my first C++ program” on the screen.include iostream

Line 4: using namespace std;

This is an important line of code because this links up the standard C++ library. When code becomes more and more complex, this line of code is also designed to differentiate similar functions, classes and variables with the same name in different libraries. In other words, with the help of “using namespace std”, it stops the complier from mixing up code with similar names and identities.

using namespace stdLine 6: int main()

Without this line of code, the program will not start. It is just like trying to start a car without a battery. The execution of all C++ programs begin with the “int main()” function in the code. It doesn’t matter where is it located in the code, without it, the program will not run.

Line 7: {

The open bracket indicates the start of the main’s function definition. It is the main area where you implement code of what you want the program to achieve.

Line 8: cout << “This is my first C++ program\n”;

In this line of code, we are asking to display “This is my first C++ program” onto the screen with the help of “cout << “. This is the body of the program. You can see that there is a “\n” in the line of code. This means I am asking for a new line after the text has been displayed.

Line 10: return 0;

This line terminates the “int main()” function and causes it to return the value of 0. For the majority of operating systems such as Windows, Mac OS X, a return value of 0 ensures that the program is terminating normally.

Line 11: }

This closed bracket indicates the end of the main’s function definition. After you have written the code in the body, you close it with a “}”.

Share this post