C++ Syntax

Syntax means the rules of the language. Here are the main ones for C++.

#include <iostream>             // preprocessor line

int main() {                    // the function main
    int age = 20;               // a statement ends with ;
    std::cout << "Age: " << age << '\n';
    return 0;
}
Output

Age: 20

The rules

  • Every statement ends with a semicolon ;.
  • A block of code is inside curly braces { }.
  • C++ is case sensitive: Age and age are different names.
  • Spaces and new lines do not matter, but formatting makes code readable.
  • Lines starting with # are for the preprocessor (#include, #define).
  • Every program has exactly one main function.

Identifiers (names)

  • They can have letters, digits and _, and can not start with a digit.
  • They can not be a keyword like int, class, while or return.
int main() {
    int 2nd = 5;
}
Output

Names.cpp: In function 'int main()':
Names.cpp:2:9: error: expected unqualified-id before numeric constant
2 | int 2nd = 5;
| ^~~

Namespaces and std::

Names of the standard library are in the std namespace. You can write std::cout every time, or use a using line:

#include <iostream>
using std::cout;            // only this name, not everything

int main() {
    cout << "Hello\n";
}
Output

Hello

Naming style

WhatCommon styleExample
Variables, functionssnake_case (or camelCase)total_marks
ClassesPascalCaseBankAccount
ConstantsUPPER_CASE or kNameMAX_SIZE

The standard library itself uses snake_case. Choose one style and keep it in the whole project.

Note: Turn on warnings with -Wall -Wextra. They find many mistakes before the program runs. Next: C++ Comments.

Congratulations! Chapter Finished. Learn more about the similar topics:
Exercises & Assignments
No Content Found.
Interview Questions & Answers
No Content Found.