C++ — Data types and type inference
C++ assigns every expression a type. An explicit string type preserves a label, while auto can infer the integer type of a calculated quantity.
A simple example
Tell a number from text
- Start with 2 and "2"
- Do this Add or join
- Result 4 and 22
#include <iostream>
#include <string>
int main() {
std::cout << 2 + 2 << '\n';
std::cout << std::string("2") + "2" << '\n';
}
4 22
Choosing a data type
| Type or declaration | Example | Use |
|---|---|---|
| std::string | std::string{"007"} |
Owns the character sequence. Include <string>. |
| int | 125 |
Stores a whole-number quantity within the int range. |
| double | 0.25 |
Stores a floating-point measurement. |
| bool | true |
Stores a logical outcome. |
| auto | auto n = 3; |
The compiler infers int from the initializer. The type remains static. |
Keep a product identifier and its price distinct
Keep the printed code 007 as text. Store the quantity and the price in cents as whole numbers so multiplication gives an exact total for this order. The std::string owns the label text. Multiplication happens on the integer operands before the stream prints the result.
A school shop sells three packs of paper at 125 cents each. Its scanner must print the code 007 exactly as it appears on the shelf. Keep the code as text and multiply the numeric quantity and price.
Run the example
Use a C++17 compiler. Run these commands from the directory containing the example. Use a Unix-style shell.
c++ -std=c++17 -Wall -Wextra lesson.cpp -o lesson
./lesson
#include <iostream>
#include <string>
int main() {
std::string product = "007";
int quantity = 3;
int price_cents = 125;
auto total_cents = quantity * price_cents;
std::cout << product << ": " << total_cents << " cents\n";
return 0;
}
007: 375 cents
The label retains both leading zeros. Three units at 125 cents cost 375 cents. The display joins the values only after the calculation.
Try it yourself
Change the code to 010 and the quantity to zero. What should stay visible?
Check your answer
The label stays 010 and the total becomes 0 cents. Treating the identifier as a number would lose its written form.