C++ Syntax

Program Structure

Every C++ program must contain a main() function. Code execution begins there.

Loading...
Output:
  • #include brings in libraries
  • using namespace std; simplifies naming (optional)

If using namespace std; is not used in the code, then it will look like this:

Loading...
Output:

You can compare the first 2 programs with each other to see the difference. It is easier and cleaner to just use using namespace std;

Semicolons

C++ statements end with a semicolon ;.

int x = 5;
cout << x;

Curly Braces {}

Code blocks are defined using curly braces.

if (x > 0) {
    cout << "Positive";
}

Braces can be omitted for single-line blocks, but are recommended.

Comments

Use comments to explain code. C++ supports:

// Single-line comment

/* 
   Multi-line 
   comment 
*/

Whitespace and Indentation

Whitespace is ignored, but indentation improves readability. Follow consistent formatting.

Output Statement

cout is used to display output:

You can chain multiple values using << (insertion operator):

Loading...
Output:

Input Statement

Use cin to read input:

int age;
cin >> age;

This reads input from the user into a variable.

Need Help?

Ask the AI if you need help understanding or want to dive deeper in any topic