C++ Syntax

Syntax is the set of rules that define how a C++ program must be written so the compiler can understand it. Every C++ program follows the same basic structure, and once you know that structure, you can read and write any C++ program.

The Basic Structure

Here is a minimal, complete C++ program:

#include <iostream>

int main(void) {
    std::cout << "Hello, World!";
    return 0;
}
Output:
Hello, World!

Breaking It Down

The #include Line

#include <iostream> tells the compiler to bring in the input/output library, which gives you tools like std::cout for printing text to the screen. Lines starting with # are called preprocessor directives, and they do not end with a semicolon.

The main Function

Every C++ program must have exactly one main function. This is where the program starts running. The int before main means the function returns a whole number, and return 0; at the end tells the operating system the program finished successfully.

Curly Braces

The curly braces { } mark the beginning and end of a block of code, such as the body of a function. Everything inside main‘s braces runs when the program starts.

Statements and Semicolons

Each instruction in C++ is called a statement, and every statement must end with a semicolon ;. The semicolon tells the compiler where one instruction ends and the next begins. Forgetting it is one of the most common beginner mistakes.

A Program With Multiple Statements

A program can contain several statements, executed one after another, top to bottom:

#include <iostream>

int main(void) {
    std::cout << "Learning C++" << std::endl;
    std::cout << "is fun!" << std::endl;
    return 0;
}
Output:
Learning C++
is fun!

Here, std::endl ends the current line, moving the next output to a new line. Notice that each statement, including each std::cout line, ends with a semicolon.

Whitespace and Case Sensitivity

C++ ignores extra spaces, tabs, and blank lines between statements, so you can format your code to be readable without affecting how it runs. C++ is also case-sensitive: main and Main are treated as completely different names.

Now that you know the basic syntax rules, the next lesson will look more closely at how to output text and values using std::cout.