Basic Syntax & Hello World
The "Hello, World!" program is a tradition in the programming world as the first program written when learning a new language. This program is simple, but it contains fundamental C++ concepts that need to be understood. In this tutorial, we will discuss the structure of a C++ program, every important component, and how everything works together.
C++ Program Structure
Every C++ program has a consistent basic structure. Here is a standard C++ program template:
#include <iostream>
int main() {
std::cout << "Hello, World!" << std::endl;
return 0;
}
Let us dissect each part of the program above in detail.
Code Example
#include <iostream>
using namespace std;
int main() {
cout << "Welcome to C++!" << endl;
cout << "This is my first program." << endl;
int count = 100;
cout << "Number of students: " << count << endl;
return 0;
}
The program above will produce the following output:
Welcome to C++!
This is my first program.
Number of students: 100
Code Explanation
1. #include <iostream>
#include is a preprocessor directive that tells the compiler to include a specific header file before the compilation process begins.
<iostream> is a header file that defines the standard input/output objects, including:
cin— For reading input from the keyboardcout— For writing output to the screen (console)cerr— For writing error messages to the screenclog— For writing log messages to the screen
The < > signs indicate that the header file is a standard library header that is part of the C++ Standard Library.
2. using namespace std;
std is a namespace that contains all the identifiers from the C++ Standard Library. Without the using namespace std; statement, you would have to write std::cout for every use of an object from the std namespace.
The difference:
// Without using namespace std
std::cout << "Hello" << std::endl;
// With using namespace std
cout << "Hello" << endl;
Note: In production projects, using
using namespace std;is often avoided because it can cause name conflicts. However, for learning and small programs, it is acceptable.
3. int main()
main() is the main function of every C++ program. It is the entry point where the program starts executing on the operating system.
Several important things about main():
- Return type
int— Indicates that the function returns an integer value - No parameters — The empty
( )means the function takes no parameters (though they can be added) - Cannot be renamed — The name
mainis mandatory - Only one per program — Each program may have only one
mainfunction
Valid alternative definitions of main():
int main() { ... } // Most common
int main(void) { ... } // Explicit no-parameter
int main(int argc, char* argv[]) { ... } // With command-line arguments
4. cout << "text" << endl;
cout is an output stream object used to print text to the screen. Here is an explanation of its components:
cout— The standard object for output (character output stream)<<— The insertion operator (also called the "stream insertion operator")"text"— The string literal to be displayedendl— A manipulator that inserts a newline (\n) and flushes the output buffer
Chaining output:
cout << "Name: " << "John" << endl;
cout << "Age: " << 25 << endl;
cout << "Height: " << 1.75 << " meters" << endl;
5. return 0;
return 0; ends the main() function and returns the value 0 to the operating system. By convention:
- Return 0 — The program executed successfully without errors
- Return other than 0 — The program encountered an error
In modern C++ (C++11 and later), if return 0; is not written explicitly, the compiler adds it automatically. However, writing it explicitly is considered good practice.
6. Semicolon (;)
The semicolon marks the end of a statement in C++. Every statement must end with a semicolon.
int x = 10; // Declaration statement
x = x + 5; // Assignment statement
cout << x << endl; // Output statement
7. Curly Braces ({ })
Curly braces define a code block (block scope). This code block is used to group several statements, such as:
- The body of a function
- The body of a loop (
for,while) - The body of a conditional (
if,else) - The definition of a class or struct
int main() { // Open main function block
int x = 10; // Inside main block
if (x > 5) { // Open if block
cout << "Big";
} // Close if block
return 0;
} // Close main block
Hello World Program with Command-Line Arguments
Here is a more complete version of the Hello World program with command-line arguments:
#include <iostream>
#include <string>
int main(int argc, char* argv[]) {
std::cout << "Program: " << argv[0] << std::endl;
std::cout << "Number of arguments: " << argc << std::endl;
if (argc > 1) {
std::cout << "Argument 1: " << argv[1] << std::endl;
} else {
std::cout << "No arguments were given." << std::endl;
}
return 0;
}
# Compile
g++ -std=c++17 -o hello hello.cpp
# Run without arguments
./hello
# Run with an argument
./hello world
Other Simple Programs
Calculating the Area of a Rectangle
#include <iostream>
int main() {
double length = 12.5;
double width = 7.3;
double area = length * width;
std::cout << "Length: " << length << std::endl;
std::cout << "Width: " << width << std::endl;
std::cout << "Area: " << area << std::endl;
return 0;
}
Variations in Writing Output
#include <iostream>
int main() {
std::cout << "One line" << std::endl;
std::cout << "Two" << " " << "lines" << std::endl;
// Using \n as a replacement for endl
std::cout << "Use \\n for a newline without flushing\n";
// Output of several data types
std::cout << "String: " << "Hello" << std::endl;
std::cout << "Integer: " << 42 << std::endl;
std::cout << "Float: " << 3.14f << std::endl;
std::cout << "Double: " << 2.718281828 << std::endl;
std::cout << "Char: " << 'A' << std::endl;
std::cout << "Bool: " << true << std::endl;
return 0;
}
Difference Between endl and \n
Both of these ways insert a new line, but there is an important difference:
// Using endl — flushes the buffer each time
std::cout << "Hello" << std::endl;
std::cout << "World" << std::endl;
// Using \n — does not flush the buffer
std::cout << "Hello\n";
std::cout << "World\n";
| Aspect | endl |
\n |
|---|---|---|
| Newline | Yes | Yes |
| Flush buffer | Yes | No |
| Performance | Slower | Faster |
| Usage | When an immediate flush is needed | For normal output |
For simple programs, the difference is not significant. However, for programs with lots of output, \n is more efficient because it does not force a buffer flush on every line.
The Compilation and Execution Process
When you write a C++ program and compile it, several stages take place:
1. Preprocessing
The preprocessor handles directives that start with #:
// Before preprocessing
#include <iostream>
#define MAX 100
// After preprocessing (simplified)
// The entire contents of <iostream> are inserted here
// MAX is replaced with 100
2. Compilation
The compiler translates the preprocessed code into assembly code (assembly language).
3. Assembly
The assembler converts the assembly code into an object file (.o or .obj) that contains machine code.
4. Linking
The linker combines the object file with the required libraries to produce an executable file.
# All stages in a single command
g++ -std=c++17 -o program program.cpp
# Stages separately
g++ -std=c++17 -E program.cpp -o program.i # Preprocessing
g++ -std=c++17 -S program.i -o program.s # Compilation
g++ -std=c++17 -c program.s -o program.o # Assembly
g++ -o program program.o # Linking
Common Beginner Mistakes
Forgetting the Semicolon
// Wrong
cout << "Hello" << endl
// Correct
cout << "Hello" << endl;
Forgetting to Include the Header
// Wrong — cout is not recognized
int main() {
cout << "Hello" << endl;
return 0;
}
// Correct
#include <iostream>
int main() {
cout << "Hello" << endl;
return 0;
}
Forgetting the Return Type
// Wrong
main() {
cout << "Hello" << endl;
}
// Correct
int main() {
cout << "Hello" << endl;
return 0;
}
Using string Without the Include
// Wrong — string is not recognized
#include <iostream>
int main() {
string name = "John";
return 0;
}
// Correct
#include <iostream>
#include <string>
int main() {
std::string name = "John";
return 0;
}
Conclusion
A C++ program starts from the main() function, uses #include to include the required headers, and every statement ends with a semicolon. cout << is used for output to the screen, endl for a new line, and return 0; indicates that the program ended successfully. Understanding this basic structure is the foundation for all C++ concepts that will be learned next.