DEV Community

Jess
Jess

Posted on

C++ Data Types

In C++, when you declare a variable you also specify its data type, which is the kind of data the variable can hold. The compiler needs to know what type of data it is because it allocates a certain amount of memory based on the type.

int year = 2020;
double gpa = 4.0;
char grade = 'A';
Enter fullscreen mode Exit fullscreen mode

There are 3 data type categories: primitive (also known as fundamental or built-in), derived, and user-defined.

Primitive Data Types

These data types are built into the compiler by default and are divided into 3 categories:

  • integral (whole numbers)
  • floating-point (fractions)
  • void* (empty set)

*Variables can not be specified as type void; it is used to declare functions with no return value.

Frequently used primitive types include:

Data Type Storage (bytes) Usage Range
int 4 integral -2,147,483,648 to 2,147,483,647
unsigned int 4 integral 0 to 4,294,967,295
long long 8 integral -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807
float 4 floating point 3.4E +/- 38 (7 digits)
double 8 floating point 1.7E +/- 308 (15 digits)
bool 1 logical (Boolean) true, false
char 1 single characters (letters, digits, symbols) -128 to 127
unsigned char 1 single characters 0 to 255

Derived Data Types

These data types are derived from the built-in types and are:

  • array
  • function
  • pointer
  • reference

Functions are defined with the data type they return. If they do not return a value, their type is void.

int sum(int a, int b) 
{
    return a + b;
}

void helloWord() 
{
    std::cout << "Hello World";
}

Enter fullscreen mode Exit fullscreen mode

A pointer stores the memory address of the data as opposed to the actual data itself.

Reference is like a pointer but is an alias to an already existing variable.

User-Defined Data Types

These are data types that you can, well, define yourself.

The 3 categories are:

  • enumerations
  • classes
  • unions

Enumerations are programmer defined types that are just integers behind the scenes. They make it easier to represent data rather than using random integers to represent values.

Each name is assigned an integer corresponding to its place in order. So here Diamonds = 0, Hearts = 1, etc.

enum Suit { Diamonds, Hearts, Clubs, Spades };
Enter fullscreen mode Exit fullscreen mode

You can set the value explicitly and each name will follow (Hearts will equal 2, Clubs = 3, etc):

enum Suit { Diamonds = 1, Hearts, Clubs, Spades };
Enter fullscreen mode Exit fullscreen mode

Classes contain components, called members, to describe and manipulate an object. Structs are similar to classes, except in structs everything is public by default; in classes the default is private.

With unions, all members share the same memory location.


I will be going more into these in future posts but in the meantime here are some articles:

References / Further Reading

Top comments (0)