Data types in C++

In C++, data types are fundamental for defining the nature and behavior of variables. They are categorized into several groups: fundamental (primitive) data types, derived data types, and user-defined data types.

Primitive Data Types

Data TypeSizeRange / ValuesExample
intTypically 4 bytes-2,147,483,648 to 2,147,483,647int a = 10;
shortTypically 2 bytes-32,768 to 32,767short b = 100;
longTypically 4 or 8 bytesDepends on system, often -2^31 to 2^31-1long c = 1000000;
long longTypically 8 bytes-2^63 to 2^63-1long long d = 1000000000;
char1 byte-128 to 127 or 0 to 255 (signed or unsigned)char e = 'A';
wchar_tTypically 2 or 4 bytesRepresents wide characterswchar_t f = L'A';
bool1 bytetrue or falsebool g = true;
floatTypically 4 bytesApproximately ±3.4E-38 to ±3.4E+38 (7 significant digits)float h = 3.14f;
doubleTypically 8 bytesApproximately ±1.7E-308 to ±1.7E+308 (15 significant digits)double i = 3.14159;
long doubleTypically 8, 12, or 16 bytesLarger than doublelong double j = 3.141592653589793238L;

Derived Data Types

Data TypeDescriptionExample
ArrayCollection of elements of the same typeint arr[10];
PointerStores memory address of another variableint* ptr;
ReferenceAlias for another variableint& ref = a;
FunctionBlock of code that performs a specific taskvoid printHello() { std::cout << "Hello"; }

User-Defined Data Types

Structures (struct)

  • Collection of different data types under a single name.
  • Syntax:
struct StructName { dataType member1; dataType member2; ... };
  • Example:
struct Person {
    std::string name;
    int age;
};
Person p1 = {"John", 30};

Unions (union)

  • Similar to structures but share the same memory location for all members.
  • Syntax:
union UnionName { dataType member1; dataType member2; ... };
  • Example:
union Data {
    int intVal;
    float floatVal;
};
Data d1;
d1.intVal = 10;

Enumerations (enum)

  • Define a set of named integer constants.
  • Syntax:
enum EnumName { value1, value2, ... };
  • Example:
enum Color { RED, GREEN, BLUE };
Color c = RED;

Classes (class)

  • Blueprint for objects, encapsulating data and functions.
  • Syntax:
class ClassName {
public:
    dataType member;
    returnType functionName(parameters);
private:
    // private members
};
  • Example:
class Car {
public:
    std::string brand;
    void start() {
        std::cout << brand << " is starting";
    }
};
Car car1;
car1.brand = "Toyota";
car1.start();