Variables, types and reading input
Course contents (20 lessons)
- Getting started
- Setting up a C++ compiler and writing your first program
- Variables, types and reading input
- Control flow, functions and indirection
- Control flow: if, switch and loops
- Functions: parameters, return values and overloading
- References and pointers
- Working with data
- Arrays and std::vector
- Working with std::string and string_view
- Classes and object-oriented design
- Structs and classes: your own types
- Constructors, destructors and RAII
- Operator overloading
- Inheritance and virtual functions
- Generic code and the STL
- Templates: writing generic code
- The STL: containers and iterators
- Algorithms and lambdas
- Ownership, moves and errors
- Smart pointers and ownership
- Move semantics and perfect forwarding basics
- Error handling: exceptions, optional and expected
- Modern C++ and a real project
- Modern C++: ranges, concepts and std::format
- Building projects with CMake
- Final project: a command-line expense tracker
C++ is statically typed
Every variable in C++ has a type that is fixed when you write the code. The compiler knows how many bytes it needs and which operations are allowed. This is the reason many bugs are caught before the program ever runs. It is also the reason you must say what you mean.
The types you will use every day
| Type | Holds | Example |
|---|---|---|
int | Whole numbers, usually 32 bits | int age = 34; |
long long | Larger whole numbers, at least 64 bits | long long big = 5'000'000'000; |
double | Decimal numbers, about 15 digits of precision | double price = 19.99; |
bool | true or false | bool done = false; |
char | One character, stored as a small integer | char grade = 'A'; |
std::string | Text of any length | std::string name = "Asha"; |
The standard says int is "at least 16 bits" and leaves the rest to the platform. In practice it is 32 bits on every machine you will touch. If the exact size matters, such as in a file format, use the fixed-width types from <cstdint>, like std::int32_t and std::uint64_t. Note the digit separator in the table: C++14 lets you write 5'000'000'000 to make long numbers readable.
Declaring and initialising
Always give a variable a value when you create it. An uninitialised local int contains whatever junk was in memory, and reading it is undefined behaviour. That means the standard places no limit on what the program may do, and it often looks fine until the day it does not.
#include <iostream>
#include <string>
int main() {
int count{3}; // brace initialisation
double rate = 0.15; // older style, still fine
std::string city{"Lahore"};
bool ready{true};
std::cout << city << " has " << count << " items\n";
std::cout << "rate: " << rate << ", ready: " << ready << "\n";
return 0;
}
I prefer braces. They have one useful safety feature: they refuse narrowing conversions. int x{3.7}; will not compile because it would lose the decimal part. int x = 3.7; compiles silently and gives you 3. The compiler stopping you is a favour.
auto and const
With auto the compiler works out the type from the value on the right. It does not make C++ dynamic; the type is still fixed, you just did not write it.
auto n = 42; // int
auto pi = 3.14159; // double
auto name = std::string{"Omar"}; // std::string
const int maxUsers = 100; // cannot be changed later
constexpr double taxRate = 0.17; // known at compile time
Use auto when the type is obvious from the right side or very long to write. Do not use it when it hides something you want the reader to see. Use const for anything that should not change. It documents intent and the compiler enforces it. I make almost every variable const unless I know it must change.
Arithmetic and its traps
The operators are + - * / %. Division of two integers gives an integer, with the fraction thrown away.
int a = 7, b = 2;
std::cout << a / b << "\n"; // 3
std::cout << a % b << "\n"; // 1
std::cout << static_cast<double>(a) / b << "\n"; // 3.5
Convert explicitly with static_cast<double>(a). Floating point numbers also have rounding error: 0.1 + 0.2 is not exactly 0.3. Never compare doubles with == when they come from calculations. Compare against a small tolerance instead.
Integer overflow is another trap. Signed overflow, such as adding one to the largest int, is undefined behaviour. Unsigned types wrap around instead, which brings its own surprises: unsigned int x = 0; --x; gives a huge number. Prefer signed types for ordinary counting.
Reading input
Use std::cin with the >> operator for single words and numbers, and std::getline for a whole line.
#include <iostream>
#include <string>
int main() {
std::cout << "Your name? ";
std::string name;
std::getline(std::cin, name);
std::cout << "Your age? ";
int age{};
if (!(std::cin >> age)) {
std::cout << "That was not a number.\n";
return 1;
}
std::cout << name << " will be " << age + 1 << " next year.\n";
return 0;
}
Notice int age{};. Empty braces give zero. Notice also the check on std::cin >> age. The expression is true if the read worked and false if the user typed letters. Always check, because a failed read leaves the stream in an error state and every later read silently does nothing.
The common mistake
Mixing std::cin >> and std::getline is the classic one. After cin >> age, the newline the user typed stays in the buffer. A following getline reads that leftover newline and returns an empty string, so it looks like the program skipped your question. Either read everything with getline and convert, or call std::cin.ignore(1000, '\n') before the getline.
Try it yourself
- Write a program that asks for a price and a quantity, as a
doubleand anint, and prints the total with 17% tax added. - Try
int x{2.5};and read the error. Then tryint y = 2.5;with-Wall -Wextraand see what the compiler says. - Add a
getlineafter reading a number and watch the skipped-question bug happen. Fix it withignore.
#include <iostream>
#include <string>
int main() {
int count{3}; // brace initialisation
double rate = 0.15; // older style, still fine
std::string city{"Lahore"};
bool ready{true};
std::cout << city << " has " << count << " items\n";
std::cout << "rate: " << rate << ", ready: " << ready << "\n";
return 0;
}
This course is free to read. Create a free account to enrol, save your progress and pick up where you left off.
Sign up free I already have an account