First programs
main, printing, variables and auto, conditions, std::array and the three kinds of loop.
- Compile and run a C++ program with g++
- Declare variables with explicit types and with auto
- Use std::array safely, and pick the right loop for the job
The smallest valid C++ program is 01main.cpp:
int main() {
return 0;
}
main is where execution starts, and its return value goes back to the shell: 0 means success. Run it and check with echo $?.
Printing
02print.cpp writes to standard output with std::cout and the << operator, which can be chained:
#include <iostream>
std::cout << "Hello," << " World!\n";
std::cout << 1 << " World!\n"; // numbers print too
#include <iostream> pastes in the declarations of the stream library — literally: lesson 12 shows that this one line expands into more than 36,000 lines before the compiler proper ever sees the program.
Variables and auto
int var1;
var1 = 10;
double var2 = 20.5;
auto var3 = var1 + var2; // deduced as double
std::cout << var3 << '\n'; // 30.5
auto asks the compiler to use the type of the expression on the right. Adding an int to a double converts the int, so var3 is a double and the program prints 30.5. Initialising at declaration, as for var2, is the habit to keep: var1 holds garbage between its declaration and its assignment.
Conditions
04condition.cpp chains if, else if and else, and nests one inside another. With a = 15 and b = 1 it prints a is greater than b! and then a is equal to 15!. The one trap is = (assignment) versus == (comparison): if (a = b) compiles, assigns, and tests the assigned value. -Wall warns about it.
std::array
A C-style array int a[3] forgets its own size when passed to a function. std::array<int, 3> keeps it, and costs nothing extra:
std::array<int, 3> my_array = {1, 2, 3};
my_array.at(0); // 1, bounds-checked: throws std::out_of_range if wrong
my_array[1]; // 2, unchecked: an out-of-range index is undefined behaviour
my_array.size(); // 3
my_array.fill(54); // every element becomes 54
The program prints 1 2 1 3 size= 3 10 54 54. Note the commented-out line std::cout << my_array — there is no << for arrays, which is why the next lessons write print functions.
Loops
for (int i = 0; i < 5; i++) { ... } // counted
for (int value : my_array) { ... } // range-based: every element
while (work_items > 0) { ... } // test first
do { ... } while (work_items > 0); // body runs at least once
The two while-loop programs show the difference. 07whileloop.cpp starts at 10 and prints 9 down to 0. 07dowhile.cpp starts at 0: the condition is false from the start, yet it prints 0 once, because a do–while checks after the body.
Try it yourself. In 05array.cpp, replace my_array.at(0) with my_array.at(3) and run it: read the exception message. Then try my_array[3] instead and compile with -fsanitize=address -g. Which of the two tells you the line number?