Shiklo Tools
PDF40
Image20
Calculators & Converters25
Text & Writing13
Developer26
Video14
Audio14
Document14
Data & Spreadsheet12
Web & SEO9
OCR & Scanning5
Archive & File12
Security & Privacy23
Health & Medical29
QR & Barcode5

C++ Syntax and Namespaces

Syntax is the set of rules for writing C++ code. The compiler is strict about them, but there are not many to learn.

Statements, semicolons and blocks

A statement is one instruction, ending with a semicolon. Statements run from top to bottom. Curly braces { } group statements into a block, such as the body of main. Every { needs a matching }, and the code inside is indented to show the structure.

#include <iostream>

int main() {
    std::cout << "One\n";
    std::cout << "Two\n";
    {
        std::cout << "Inside a block\n";
    }
    return 0;
}
Output
One
Two
Inside a block

Case and whitespace

C++ is case sensitive: cout, Cout and COUT are different names. Keywords such as int, if and return are lower case. Spaces and line breaks between the parts of a statement do not matter to the compiler; use them to make the code readable.

Namespaces

Large programs and libraries use many names. A namespace groups names so that two libraries can both have a function called print without a clash. The standard library is in std, and :: reaches a name inside a namespace: std::cout. You can make your own:

#include <iostream>

namespace geometry {
    double square(double x) { return x * x; }
}

namespace finance {
    double square(double x) { return x * x * 100; }   // a different square
}

int main() {
    std::cout << geometry::square(3) << "\n";
    std::cout << finance::square(3) << "\n";
    return 0;
}
Output
9
900

using

using std::cout; makes one name usable without std::; using namespace std; does it for every name in std. They save typing in small programs. Never put using namespace std; in a header file, because every file that includes it would get all of std's names.

#include <iostream>
#include <string>
using std::cout;
using std::string;

int main() {
    string language = "C++";
    cout << "Learning " << language << "\n";
    return 0;
}
Output
Learning C++

Practice exercises

  1. Write a namespace school with a function that prints the school's name, and call it from main.
  2. Change cout to Cout and read the error.
  3. Remove the closing } of main and see where the compiler reports the problem.