C++ Data Types

Fundamental building blocks for variables in C++

Primitive Data Types

TypeSize (bytes)RangeExample
int4-2,147,483,648 to 2,147,483,647int age = 25;
float4±3.4e±38 (~7 digits)float pi = 3.14f;
double8±1.7e±308 (~15 digits)double precise = 3.1415926535;
char1-128 to 127 or 0 to 255char grade = 'A';
bool1true or falsebool isValid = true;
voidN/AN/Avoid printMessage();

Type Modifiers

Size Modifiers

short int smallNum;     // At least 2 bytes
long int bigNum;        // At least 4 bytes
long long int hugeNum;  // At least 8 bytes

Sign Modifiers

signed int normal;     // Can be positive/negative (default)
unsigned int positive;  // Only positive values

Derived Data Types

Arrays

int numbers[5];          // Declaration
float temps[] = {36.5, 37.0};  // Initialization

Pointers

int num = 10;
int* ptr = #  // Pointer to num

References

int original = 5;
int& ref = original;  // Reference to original

User-Defined Types

Structures

struct Person {
  string name;
  int age;
  float height;
};

Person p1;
p1.name = "Alice";

Classes

class Rectangle {
  private:
    int width, height;
  public:
    void setDimensions(int w, int h) {
      width = w;
      height = h;
    }
};

Type Conversion

Implicit Conversion

int num = 10;
double d = num;  // Automatically converted

Explicit Conversion

double pi = 3.14159;
int approx = (int)pi;  // C-style cast
int precise = static_cast<int>(pi);  // C++ cast

Type Aliases

typedef unsigned long ulong;  // Traditional
using Celsius = float;        // Modern (C++11)

ulong bigNumber;
Celsius currentTemp = 23.5;