CP C++

C++: Variables & Data Types

What you will learn

How C++ declares variables with explicit types, the difference between primitive types and std::string, and how type sizes vary by platform.

C++ is statically typed — the compiler checks types at compile time. Every variable must have a declared type, and that type cannot change.

#include <string>

int age = 25;                      // int
double height = 5.6;               // double (floating point)
bool isStudent = true;             // bool
std::string name = "Alice";       // std::string from <string> header
char initial = 'A';                // char (single character)

Common types and their sizes

Type Typical Size Example Notes
int 4 bytes 42 Platform-dependent (usually 32-bit)
double 8 bytes 3.14 Double-precision float
float 4 bytes 2.5f Single-precision (use f suffix)
bool 1 byte true Can be true or false
char 1 byte 'A' ASCII character (use single quotes)
std::string variable "hello" Object from <string> header (use double quotes)

std::string is not a primitive — it is a class from the C++ Standard Library. You must #include <string> to use it.

auto keyword (C++11+)

C++11 introduced type inference with auto:

auto x = 42;          // int
auto y = 3.14;        // double
auto name = "Alice";  // const char* (not std::string!)

Watch out: auto for a string literal gives const char*, not std::string. Use auto s = std::string{"hello"}; if you want the string type.

Common mistakes

  • Forgetting #include <string> and getting a compile error about std::string being unknown
  • Using single quotes for strings ('hello') — single quotes are for char, double quotes for string literals
  • Assuming int is always 32 bits — on some embedded platforms int can be 16 bits; use <cstdint> types like int32_t for portability
  • Confusing = (assignment) with == (equality) in conditions

Quick check below!