TExcelTAD
Home › C++ › C++ Syntax

C++ Syntax

Let's take a careful look at the building blocks of a C++ program. Here is a small program we will dissect:

cpp · try it yourself
#include <iostream>
using namespace std;

int main() {
    cout << "Learning the syntax\n";
    return 0;
}
Learning the syntax

Line by line

Line Meaning
#include <iostream> A preprocessor directive that makes the input/output library available.
using namespace std; Lets you write cout instead of std::cout.
int main() Declares the main function, where execution begins. int is its return type.
{ ... } Curly braces mark the start and end of a block of code (here, the function body).
cout << "..."; A statement that prints text. Every statement ends with ;.
return 0; Ends main and reports success.

Namespaces and std::

Everything in the C++ standard library lives in a namespace called std. A namespace is like a surname: it prevents name clashes between libraries. You can refer to library names in two ways:

cpp · try it yourself
#include <iostream>

int main() {
    std::cout << "Fully qualified name\n";

    using std::cout;   // import just this one name
    cout << "Short name after a using-declaration\n";
}
Fully qualified name
Short name after a using-declaration

Note: using namespace std; is fine for small examples and exercises, and you will see it in many lessons here. In large projects and especially in header files, prefer std:: or targeted using std::cout; declarations so that names do not collide.

Statements and semicolons

A statement is one instruction. C++ does not care about line breaks — it uses the semicolon to tell where a statement ends. That means these two lines are equivalent, although the first is much easier to read:

cpp
std::cout << "Hi";
std::cout
    <<
    "Hi"
    ;

Forgetting a semicolon is the most common beginner error. The compiler usually reports it on the next line, because that is where it realises something is missing.

Whitespace and case sensitivity

  • Spaces, tabs and blank lines are ignored (except inside strings). Use them to make code readable.
  • C++ is case-sensitive: main, Main and MAIN are three different names. Cout will not compile.

Blocks

Curly braces group statements. Functions, if statements and loops all use blocks. By convention, code inside a block is indented by 4 spaces:

cpp · try it yourself
#include <iostream>
using namespace std;

int main() {
    cout << "Outer block\n";
    {
        cout << "  Inner block\n";
    }
    cout << "Back outside\n";
}
Outer block
  Inner block
Back outside

Test yourself

What character ends most C++ statements?

  1. .
  2. :
  3. ;
  4. Newline

Which namespace contains the standard library?

  1. stl
  2. std
  3. cpp
  4. lib

Is Cout the same as cout in C++?

  1. Yes, C++ ignores case
  2. No, C++ is case-sensitive
  3. Only on Windows
  4. Only inside main