C++ - Disecting Hello World
Chapter 2: Disecting Hello World
In this chapter, we will learn how to write a simple “Hello World” program in C++. We will start by writing a program that prints “Hello World” to the console, and then we will add some comments and formatting to make the code more readable.
Writing Hello World
To write a “Hello World” program in C++, we need to create a new C++ file and write the following code:
Let’s break down the code:
#include <iostream>
: This line includes theiostream
header file, which provides input and output functionality.int main()
: This line defines the main function, which is the entry point of the program. furthermore, it specifies the return type of the function asint
. Theint
data type is used to represent integers and this function returns an integer value.using namespace std;
: This line allows us to use thecout
object from thestd
namespace without having to prefix it withstd::
. The concept of namespace is important in C++ and it helps to avoid naming conflicts. In this case, we are using thecout
object from thestd
namespace.cout << "Hello World!" << std::endl;
: This line prints the string “Hello World!” to the console. endl is a manipulator that adds a newline character to the output.return 0;
: This line indicates that the program has finished executing and returns a value of 0. It can return any value, but in this case, we are returning 0 as this is the exit code for a successful program execution.
Compiling Hello World
To compile the “Hello World” program, we need to use a C++ compiler. A C++ compiler is a software tool that translates the C++ code into machine code that can be executed by a computer. You can use runner extension in VS Code to compile and run the code.
Running Hello World
To run the “Hello World” program, we need to compile it and then run the compiled executable. Here are the steps to do this:
-
Open a terminal.
-
Navigate to the directory where the “Hello World” program is saved.
-
Compile the program using the following command:
OR you can use runner extension in VS Code to compile and run the code.
-
Run the program using the following command:
Hello World with Comments
Now that we have written a “Hello World” program, let’s add some comments to make the code more readable. Here’s the updated code:
- The
//
symbol is used to add comments to the code. Comments are ignored by the compiler and are only meant for human readers.
Summary
In this chapter, we have learned how to write a simple “Hello World” program in C++. We have also learned how to compile and run the program. By the end of this chapter, you should have a good understanding of how to write and run a “Hello World” program in C++.