</>CodexBash
C++
C++Beginner8 min

Your first C++ program

What C++ is, the shape of a C++ program, compiling with g++, printing with cout, and reading compiler errors.

C++ began as C with additions and grew into one of the most capable languages there is. It is fast like C, but gives you ready-made tools: text that manages itself, growable arrays, maps, sorting and classes. Games, browsers, trading systems and most competitive programming are written in it.

Hello, world#

#include <iostream>

int main() {
    std::cout << "Hello, world\n";
    return 0;
}
  • #include <iostream> brings in input and output.
  • int main() is where the program starts.
  • std::cout is the output stream, and << sends a value to it. std is the standard library's namespace, the family name for everything built in.
  • \n ends the line. Statements end with ;.

using namespace std#

Writing std:: everywhere gets long, so you will often see:

#include <iostream>
using namespace std;

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

That is fine in small programs and practice solutions, and CodexBash's judge adds it for you. In large projects people prefer the full std:: names, to avoid clashes. return 0; at the end of main may also be left out; it is assumed.

Compiling and running#

g++ -std=c++20 -Wall -O2 hello.cpp -o hello
./hello

-std=c++20 picks the modern version of the language, -Wall turns on helpful warnings, and -O2 makes the program fast.

Printing several things#

<< chains, so a single line can print text and values:

int age = 21;
double price = 99.5;
cout << "Age: " << age << ", price: " << price << "\n";

No placeholders to match up, unlike C's printf: cout knows each value's type.

endl also ends a line, but forces the output out immediately, which is slow when printing many lines. Prefer "\n".

Comments#

// to the end of the line
/* across
   several lines */

Reading an error#

hello.cpp:5:5: error: 'cot' was not declared in this scope; did you mean 'cout'?

File, line, column, then the message, and often a suggestion. Fix the first error and recompile. C++ errors involving templates can be pages long; the first line naming your file is the one that matters.

Key points#

  • #include <iostream> and cout << value print.
  • using namespace std; saves typing std::.
  • Compile with g++ -std=c++20 -Wall -O2.
  • Use "\n" rather than endl for speed.

Next: variables, types, and letting the compiler work types out.

Create a free account to track your progress