C++ · Variables, types and I/O
Static types in C++, sizes of the built-in types, integer overflow, auto, const, and reading input with cin.
In Python a name can point to anything. In C++ every variable has a static type that is fixed at compile time.
| type | typical size | notes |
|---|---|---|
int | 4 bytes | about ±2.1 billion |
long long | 8 bytes | use it for big counts |
double | 8 bytes | the default floating-point type |
char | 1 byte | a single character |
bool | 1 byte | true / false |
autolets the compiler deduce the type from the initialiser. The type is still static.constmakes a variable read-only.- Overflowing a signed integer is undefined behaviour, unlike Python’s unlimited ints. Use
long longwhen values can get big. std::cin >> xreads input. I used astd::istringstreambelow so the example runs without typing anything.
#include <iostream>
#include <sstream>
#include <limits>
int main() {
const double pi = 3.14159;
auto count = 42; // int
auto ratio = 0.75; // double
long long big = 3'000'000'000LL;
std::cout << "int max: " << std::numeric_limits<int>::max() << '\n';
std::cout << "big: " << big << ", count: " << count << ", ratio: " << ratio << '\n';
std::cout << "7/2 = " << 7 / 2 << ", 7.0/2 = " << 7.0 / 2 << '\n';
std::istringstream in("Sahaj 19");
std::string name; int age;
in >> name >> age;
std::cout << name << " is " << age << ", area of r=2 circle: " << pi * 2 * 2 << '\n';
}
Output:
int max: 2147483647
big: 3000000000, count: 42, ratio: 0.75
7/2 = 3, 7.0/2 = 3.5
Sahaj is 19, area of r=2 circle: 12.5664Sources
- Fundamental types — cppreference.com
- Placeholder type specifiers (auto) — cppreference.com
- Introduction to fundamental data types — LearnCpp.com