Sahaj.blogs
6 Nov 2023 · StudyPhase 2 · C++

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.

typetypical sizenotes
int4 bytesabout ±2.1 billion
long long8 bytesuse it for big counts
double8 bytesthe default floating-point type
char1 bytea single character
bool1 bytetrue / false
  • auto lets the compiler deduce the type from the initialiser. The type is still static.
  • const makes a variable read-only.
  • Overflowing a signed integer is undefined behaviour, unlike Python’s unlimited ints. Use long long when values can get big.
  • std::cin >> x reads input. I used a std::istringstream below 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.5664

#cpp#types

Sources

  1. Fundamental types — cppreference.com
  2. Placeholder type specifiers (auto) — cppreference.com
  3. Introduction to fundamental data types — LearnCpp.com