DMarlon Studio

Lesson 2 · 2 of 20

Variables, types and auto · C++

Declare C++ variables with int, double, char, bool and std::string, protect values with const and let auto work out the type.

C++ · Variables, types and auto in DMarlon Studio: the example's code and its output in the terminal

In C++ every variable has a fixed type, written before its name: int for whole numbers (age), double for numbers with decimals (height), char for a single character in single quotes ('A') and bool for true or false. It is good practice to always give them a starting value.

`std::string` holds text in double quotes and needs #include <string>. When you print a bool with std::cout you get 1 (true) or 0 (false); lesson 7 shows how to print true and false instead.

A variable can change its value (age = age + 1) but never its type. The compiler checks types before anything runs, so it catches many mistakes early. With `const`, the value is fixed: if you try to change vat, the program does not compile.

`auto` lets the compiler work out the type from the value: 49.90 makes price a double and 3 makes units an int. It is handy, but the type is still fixed. total mixes both, and the result is a double.

`sizeof` tells you how many bytes a type takes in memory: on a modern computer an int takes 4 and a double 8.

Code · main.cpp

#include <iostream>#include <string>int main() {    // Each variable has a type, a name and (always, better) a value.    int age = 34;    double height = 1.78;    char grade = 'A';    bool member = true;    std::string name = "Lucia";    std::cout << name << " is " << age << " years old\n";    std::cout << "Height: " << height << " m, grade " << grade << '\n';    std::cout << "Member: " << member << '\n';  // a bool prints 1 or 0    // A variable can change its value, but never its type.    age = age + 1;    std::cout << "Next year: " << age << '\n';    // const: a value that must not change.    const double vat = 0.21;    // auto: the compiler deduces the type from the value.    auto price = 49.90;  // double    auto units = 3;      // int    auto total = price * units * (1 + vat);    std::cout << "Total with VAT: " << total << '\n';    // sizeof tells how many bytes a type takes in memory.    std::cout << "int: " << sizeof(int) << " bytes, double: " << sizeof(double) << " bytes\n";    return 0;}

Output · c++ -std=c++17 main.cpp -o main && ./main

Lucia is 34 years old
Height: 1.78 m, grade A
Member: 1
Next year: 35
Total with VAT: 181.137
int: 4 bytes, double: 8 bytes

Key points

  • Type, name and value: int age = 34;.
  • int, double, char, bool and std::string are the basic types.
  • const stops a value from changing.
  • auto deduces the type from the starting value.
  • A variable never changes its type.

Exercise

Add const int maxPlayers = 4; and auto players = 3;, print how many places are still free, then try to assign a new value to maxPlayers and read the compiler error.