C++ - Hello World
Before starting the abcd of C++ language, you need to learn how to write, compile and run the first C++ program.
To write the first C++ program, open the C++ console and write the following code:
Example
#include <iostream>
int main() {
std::cout << "Hello, World!" << std::endl;
return 0;
}
Explanation
- The #include <iostream> line is a preprocessor directive that tells the compiler to include the input/output stream (iostream) header file. This header file provides functionality for reading from and writing to the standard input/output streams.
- The int main() function is the entry point of a C++ program. Execution of the program starts from this function.
- The opening brace { indicates the beginning of the function's code block.
- std::cout is an output stream object provided by the iostream library. It represents the standard output stream.
- The << operator is the insertion operator, which is used to insert data into the output stream. Here, we insert the string "Hello, World!" into std::cout.
- std::endl is used to insert a newline character and flush the output stream. It ensures that the output is displayed immediately.
- The closing semicolon ; marks the end of the statement.
- The closing brace } indicates the end of the function's code block.
- return 0; is used to return an exit status to the operating system. A return value of 0 generally indicates successful execution of the program.
To run this code, follow these steps:
- Set up a C++ development environment with a compiler (as mentioned in the previous response).
- Create a new source file with a .cpp extension, e.g., hello.cpp.
- Copy the above code into the hello.cpp file.
- Open a terminal or command prompt and navigate to the directory where the hello.cpp file is located.
- Compile the code using the C++ compiler. For example, if you are using GCC, run g++ hello.cpp -o hello to generate an executable named hello.
- Run the executable by executing ./hello on Linux/macOS or hello.exe on Windows.
- The program should display "Hello, World!" as output.
This example demonstrates the basic structure of a C++ program, including including the necessary header, defining the main function, and using the output stream to display a message.