The Parts of a C++ Program

Every C++ program in this course starts with the same few lines. Let's look at each part once, so they are never a mystery.

#include <iostream>
using namespace std;

int main() {
    cout << "Learning C++!\n";
    return 0;
}

Output

Learning C++!

#include <iostream>

This line brings in the iostream library: ready-made code for input and output streams. Without it, C++ doesn't know what cout is.

Think of it like this: #include is like taking a toolbox off the shelf before you start working. <iostream> is the toolbox with the screen and keyboard tools.

using namespace std;

All the standard C++ tools live in a group called std (short for standard). The full name of cout is really std::cout. This line says: “I'm using the std group, so let me write just cout.”

Without that line, you write std:: in front. This program does exactly the same thing:

#include <iostream>

int main() {
    std::cout << "Hello without using namespace!\n";
    return 0;
}

Output

Hello without using namespace!

Tip: In big projects many programmers prefer writing std:: every time. In this course we use using namespace std; to keep the code short and easy to read.

int main() { ... }

main is where your program starts. When you run the program, C++ goes into main and runs the lines inside it from top to bottom.

  • The curly braces { } mark the start and the end of main. Everything between them belongs to it.
  • int means main gives back a whole number when it finishes.

return 0;

This is the number main gives back. 0 means “everything went fine”. (You may leave it out at the end of main – C++ then returns 0 for you – but it is good to write it.)

Comments

A comment is a note for humans. The compiler ignores it. Use comments to explain your code:

#include <iostream>
using namespace std;

int main() {
    // This is a one-line comment
    cout << "Comments are ignored\n"; // a comment at the end of a line

    /* This is a comment
       that spans many lines */
    cout << "Done\n";
    return 0;
}

Output

Comments are ignored
Done

Mistakes and error messages

If you make a mistake, the compiler refuses to build the program and shows an error message. Here we forgot the semicolon:

#include <iostream>
using namespace std;

int main() {
    cout << "Oops"
    return 0;
}

Output (the program does not compile)

main.cpp:5:19: error: expected ';' after expression
    cout << "Oops"
                  ^
                  ;

Read it slowly: it gives the line number (main.cpp:5) and says it expected a ';'. Error messages look scary, but they are your friend. They tell you where to look.

Common mistake: C++ is case-sensitive: cout works but Cout or COUT does not. The same goes for main, return and everything else.

HOME LABS COMMUNITY DASHBOARD