Summary
A type fixes not only how many bytes a datum occupies, but also how its bits are read: the same byte is the letter “A” for a char and the number 65 for an int. This lesson completes the basic types with characters and Booleans, and studies the passage from one type to another: implicit conversions, which the compiler performs without being asked and which can lose information; explicit conversion with static_cast; and brace initialization, which rejects losses. It ends with constants, const and constexpr, which turn an intention (“this value does not change”) into a guarantee that the compiler verifies, and with literals and auto, which decide the type of a value written in the source code.
Learning objectives
- Use the numeric code of a character to compute with it, for example to obtain the value of a digit read as a character.
- Predict the result of an implicit conversion between integers, reals and Booleans, and write the explicit conversion with
static_cast. - Explain why brace initialization rejects the conversions that lose information, and what GCC does in each case.
- Declare with
constorconstexprevery value that must not change, and distinguish one keyword from the other. - Deduce the type of a literal (
5,5u,5.0,5.0f,'5',"5") and the type thatautoassigns to it.
The type as an interpretation
The lesson Variables and memory presented the variable as a cell with a name, a type and a value, and the lessons Integers and their representation and Floating-point numbers showed that inside the cell there are no numbers but bits, and that the type says how to read them. This lesson carries that idea to its consequence: if the type is the rule for reading, then the same bits mean different things depending on the type with which they are read, and passing a value from one type to another, which in C++ is called a conversion, is changing the rule. Some conversions preserve the value (the integer 7 becomes the real 7.0 without losing anything); others alter it (the real 2.7 becomes the integer 2). From this follows the question that runs through the lesson: in each conversion, is the value preserved, and who checks it?
Loading the content…
Completed
Sign in to save your progress