C++ Data Types: Primitive, Derived and User-defined Types

Cpp-Data-Types.jpg

Developers designed and refined C++ data types to represent and store different real-world entities in the programming language, thus making programming more practical and efficient. Even using the wrong built-in type, even something as simple as int vs double, can silently break your code. C++ provides primitive data types to work with various types of data. There are three subdivisions for those types, such as Primitive (Built-in) Types, Derived Data Types, and User-Defined Data Types. Modifiers and advanced features like typedef and enumerations also support them.

We will learn about all C++ types in this article, with sample codes, performance tips, and use cases, so that you can code more cleanly, quickly, and reliably. Don’t allow a simple data type to get you into a hidden bug. Mastering data types in C++ is essential to writing safe and optimized code.

Table of Contents:

What are Data Types in C++?

C++ data types define the type of data a variable can store, such as int, float, bool, char, etc. These data types help the compiler to allocate the right amount of memory and apply the suitable corrections to it.

Types of Data Types in C++

C++ data types are divided into three broad categories: Primitive data types, derived data types, and finally, user-defined data types. Each of these categories serves a different and special purpose.

  • Primitive (built-in) data types in C++ are the most basic types, such as integers, floating-point numbers, characters, and booleans, which form the basis for storing and manipulating data in C++.
  • Programmers derive data types from primitive types to create structures such as arrays, pointers, functions, and references, thereby enabling more complex data handling and efficient memory usage.
  • User-defined data types in C++ give developers the flexibility to create custom types like structs, classes, unions, enums, and type aliases, helping organize and manage more complex data in a program.

Let us understand each C++ data type in extensive detail in the coming sections.

Primitive Built-in Types in C++

C++ has primitive built-in types that are the most basic data types. The compiler provides these built-in data types to create variables and represent primitive values. Some of the primitive types are: int (integer), float and double (decimal or floating point), char (single character), bool (true/false), void (the non-value used mostly in functions that return nothing), etc. There are fundamental types necessary for arithmetic, decision making, and the control flow of programs. They are the building blocks of complex data structures and custom types.

Data Type Description Example
int Integer numbers
int a = 10;
float Single-precision decimal numbers
float b = 5.5;
double Double-precision decimal numbers
double c = 9.99;
char Single character
char d = 'A';
bool Boolean value (true/false)
bool e = true;
void No value (used for functions)
void func();

Now, let us discuss in more detail these data types in C++: 

1. int (Integer Type)

The int data type stores whole numbers, i.e., ( aka integer type), positive and negative numbers without decimals. Among all data types in C++, int is one of the most commonly used.

Example:

Cpp

Output: 

datatype-int

The above C++ program declares an integer variable age with a value of 25, and you can use cout in C++ to print this value.

2. float (Floating Point Type)

The float data type in C++ refers to decimal numbers under single precision real numbers, i.e., real numbers that can have a fractional part, not as accurate/ big as double. Programmers usually use float when memory demands are not very high, thus balancing precision with efficiency. It takes 32 bits of memory and can represent a minimum of 1.5 × 10−45 and a maximum of 3.4 × 1038.

f suffix for float: Tells the compiler that the number is a float literal instead of a double.

Example: 

Cpp

Output:

datatype-float

The above code declares a variable named temperature, with 36.6f as a value of float type, and the cout statement displays the current temperature value on the console as  “Temperature: 36.6”. And finally, the program returns 0, indicating a successful completion.

3. double (Double Precision Type)

C++ represents a decimal number in double precision, and programmers use the double data type in programming to achieve greater accuracy than float. Double is a 64-bit type, so it can store a larger range of values and represents all values better. Double is better for specific precision calculations. It is considered one of the most accurate numeric data types in C++.

l or L suffix for long double: Tells the compiler that the number is a long double literal for higher precision.

Example: 

Cpp

Output: 

datatype-double

The above code demonstrates the use of double in C++. Here, the variable pi is declared and initialized with a value of 3.1415926535. However, the double provides double precision; it can store more decimal places than a float. Using cout, the program prints the pi values and ends by returning 0. 

4. char (Character Type)

The char data type stores a single character in single quotes ‘ ‘, which may include letters, digits, or symbols, and the program stores it as an integer value according to ASCII. For example, when you store the character ‘A’, the system represents it in memory as 65. Although the char data type is a 1-byte data type is used quite often for characters in strings, also for user input and display output. Characters are therefore essential data types in C++ for handling text and strings.

Example: 

Cpp

Output: 

datatype-char

The above code demonstrates the char data type in C++. Here, the program declares a variable named grade with the character ‘A’, and the variable stores this single character in memory. Then, the program uses cout to print the value of the grade.

5. bool (Boolean Type)

Bool stores a boolean value:

  • True is represented by 1.
  • False is represented by 0.

Boolean is used for decision-making in conditional statements like if, while, if-else, and loops. Being a true/false value, bool is among the simplest yet powerful data types in C++.

Example:

Cpp

Output: 

datatype-bool

The above code demonstrates the bool declaration in C++. The program declares a variable isPassed and sets it to true, which represents a logical “yes” or successful execution. In memory, the system stores the value true as 1, and using cout, the program displays this stored value on the console. If a program ends with a return 0, it indicates a successful program. 

6. void (Empty Type)

Void denotes no value and is used when a function does not return any value. It informs the compiler that the function executes an operation but does not return any value to the user. The void type is also used for pointers when the type of the data is not specified (void*). It’s also a necessity for purposes such as defining functions whose goal is to be executed without returning a value to the script.

Example: 

Cpp

Output: 

datatype-void

The above code demonstrates the void return type in a function. The function greet(), defined with void, does not return a value. It just prints the “Hello world!” inside that function. To the console. In the main method, we call greet(), which runs the print statement. Finally, the program ends with a return 0, denoting successful execution.

7. Wide Character 

Wide characters are used for larger sets that cannot be represented by normal character types (which are 1 byte and ASCII-based). Using the wide character set. In C++, wide characters are represented with the wchar_t type, which may store Unicode or other multi-byte character sets.

They’re called “wide” characters and are helpful with internationalization, emoji, Unicode characters, and languages with huge alphabets like Chinese, Japanese, etc.

Example: 

Cpp

Output: 

Wide Character as Data Types in C++

The above example of a C++ program demonstrates the usage of wide characters and wide strings using wchar_t and wstring. The Lprefix denotes the emoji ‘😊’ and wide literals. Instead of cout, you use wcout to display wide characters properly. This enables the program to manage and present Unicode characters such as emojis and non-ASCII text.

Note: It’s important to note that in C++, built-in types like int, float, double, char, and bool are not automatically initialized. If you declare a variable without assigning a value, it may contain garbage values from memory. Always initialize variables to avoid unexpected behavior.

Unsigned and Signed Variants of Primitive Data Types in C++

In C++, the int data type is commonly used for storing whole numbers, but it comes in different variants that beginners often find confusing. These include short, int, long, and long long, each of which can be signed (can store negative and positive values) or unsigned (can store only positive values). Choosing the correct variant is important because it affects both the range of values you can store and memory usage. Choosing signed or unsigned wisely ensures the correct use of numerical data types in C++.

Type Size (Typical) Range (Signed) Range (Unsigned)
short 2 bytes -32,768 to 32,767 0 to 65,535
int 4 bytes -2,147,483,648 to 2,147,483,647 0 to 4,294,967,295
long 4 or 8 bytes* Depends on system Depends on system
long long 8 bytes -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807 0 to 18,446,744,073,709,551,615
*The size of long depends on the system (4 bytes on most 32-bit systems, 8 bytes on many 64-bit systems).
  • Always choose the type based on the range of values you need and memory considerations.
  • Signed types store both negative and positive numbers.
  • Unsigned types store only positive numbers but can hold larger maximum values.

Derived Data Types in C++ 

In C++, the derived data types are the types that are built from the primitive data types. The derived data types include data types like arrays, functions, pointers, and references. These data types are efficient for data handling and manipulation. Derived data types in C++ extend the power of basic types by enabling advanced storage and referencing.

1. Array 

An array is a collection or group of elements of the same type stored in contiguous memory locations. Arrays are used when multiple values of the same type that are need to be stored and accessed using an index. 

Example: 

Cpp

Output: 

datatype-array

The following program shows how to use array data types in C++. Here, an integer type array is declared with the name numbers, which has 3 elements: 10, 20, and 30. Arrays are used to store multiple values of the same type in a single variable. Then the program accesses and prints the first element of the array, using 0 as an index. Using cout, the  “First number: 10” is displayed. The program returns with a return 0, indicating successful execution.

2. Function

Functions are reusable blocks in code by accept parameters, and functions return values. It is different from the straightforward data types in C++ we learnt about till now. Now only it not only holds data, but it also performs some operations on this data in the same function call.

Example:

Cpp

Output: 

datatype-function

The above program demonstrates the function declaration in C++. Here, the add is declared as a function that takes two integers, a and b. Inside the main function, the add(5, 10) is called, which returns 15. The result is printed using cout, producing the output as Sum: 15.

3. Pointer

A pointer is a variable that is used to store the memory address of another variable. Pointers are powerful because they allow dynamic memory allocation, efficient access and modification of arrays, passing large data to functions without copying, and implementing advanced data structures like linked lists and trees.

Example: 

Cpp

Output:

typedef-pointer

In C++, we used a pointer to do this program by initializing num = 42. Then, declare a pointer ptr to receive the address of num using the & operator. In this case, we use the *ptr expression to dereference the pointer, which allows us to access the value stored at that memory address. The output of the program is: Value using pointer: 42.

4. Reference 

In C++ Data Types, a reference variable is another name for an existing variable. The reference is implemented to store the address, which is similar to a pointer.  Reference is declared as ampersand (&) next to the type. 

Syntax:

type& reference_name = existing_variable;

(&) indicates the reference, while type declares the datatype(int, float, string) of the variable being referenced, reference_name refers to the name of the reference, and existing_variable is the variable that mentions the variable that the reference refers to. 

References are a safer alternative as they save the original data from modification.

Example: 

Cpp

Output:

datatype - reference

Here, num is an integer variable with 7, and ref declares the memory location of the variable. In the above code, if we change the ref value, it also modifies the value of num. 

Pointers vs Reference Data Types in C++

Before we move forward with user-defined data types in C++, as a beginner, you might be confused between pointers and references. Here is a detailed table of differences between pointers and references.

Aspect Pointer Reference
Definition A variable that stores the memory address of another variable. An alias for an existing variable.
Syntax Declared using * (e.g., int* ptr;). Declared using & (e.g., int& ref;).
Nullability Can be null (point to nothing). Cannot be null; must always refer to a valid object.
Reassignment Can change to point to different variables during its lifetime. Once initialized, always refers to the same variable.
Memory Access Requires dereferencing with * to access value. Accesses value directly like a normal variable.
Indirection Levels Supports multiple indirection (pointer to pointer). Only single level of reference.
Use Case Dynamic memory management, arrays, function arguments. Safer alias for a variable, improves readability.

User-Defined Data Types in C++

In C++, the user-defined data types are created by the developers; these data types allow the developers to create their data structures based on built-in types. These data types, including struct, union, class, and enum, help in organizing complex data. User-defined data types in C++ are crucial for object-oriented programming and abstraction.

1. Struct

Struct (short for structured) is a means to group multiple variables of different types under one name, making them easier to manage as one element. Most useful when we need to represent something that has multiple properties, like a student or employee, or a book. All members of a struct are public by default and can be accessed with the dot (.) operator. Structures enhance code readability with complex data.

Example: 

Cpp

Output: 

datatype-struct

The above code demonstrates the declaration of a struct. Here we declare Student as a struct, which takes a Student ID and a Student grade. The student ID is initialized as an Integer, and the student grade is initialized as a character. By creating the object s1 and accessing its members using the dot operator.

2. union

A union is like a struct, but unlike a struct, it has shared memory for all its members. That is, all of the members of a union share the same memory space, and only one of them can contain a value at any point. So, when you assign a new value to one member, that existing value is overwritten; you can save memory when only one of the members is needed at a time. So, Unions are used where memory optimization is needed & and are mostly used in embedded systems or low-level programming.

Example:

Cpp

Output: 

data type-union

The above C++ program demonstrates a union. As you see, the union Data consists of two members – an integer i and a float f, utilizing the same memory. At first, i is equal to 10, so the output is “Integer: 10”. Then, we set f to 3.14, which overwrites what was previously stored in i, so when we print it, we get “Float: 3.14,” indicating that the union only holds a single value at a time.

3. Class

A class is like a struct, but its members are private by default. It also supports encapsulation, meaning data is only modified or accessed through its public functions. Classes act as blueprints for objects, and they are one of the fundamentals of object-oriented programming (OOP).

Example: 

Cpp

Output: 

data types-class

This is a program that defines a class Car that has a public variable brand, and a function display() which prints out the brand. In the main function, the Car class creates an object c1, where brand is set to “Toyota” and the display function is called, which prints the output as Brand: Toyota.

4. enum (Enumeration)

For better code readability, the enum defines a set of named integer constants

Example: 

Cpp

Output: 

data types-enum

In the above code, the enum day is declared, and it assigns the values starting from 0 (sun = 0, mon = 1,…). Today is set to Monday, which means it displays 1 as an output. 

5. Typedef Defined Data Type

Typedef in C++ is used to define a new name (alias) for other data types. It improves code readability and makes it easier to change types in larger programs. For this purpose, the keyword typedef is used

example:

Cpp

Output: 

Data types-typedef

This typedef defines uint as an unsigned int. This cleans up the code better and is easier to manage, especially when using complex types multiple times.

Useful Resources:

Get 100% Hike!

Master Most in Demand Skills Now!

Conclusion

There are three categories of data types in C++: Primitive Built-in Data Types, Derived Data Types, and User-Defined Data Types. Primitive elements (such as int, float, char) and derived elements (array, pointer, function) go into the elementary modeling of the dialect. User-defined Types Developers use user-defined types to create custom data structures like classes, structs, unions, enums, etc. Understanding the purpose of these different data types helps in organizing and optimizing data in a program. A strong foundation in data types in C++ will directly improve both efficiency and readability of your code.

You can learn more about C++ in the C++ article, and also explore C++ Interview Questions prepared by industry experts.

C++ Data Types – FAQs

1. What is the difference between int and double in C++?

The int data type means you can only use whole numbers without decimals. On the other hand, double means floating-point numbers that require high precision with decimal values. 

2. When should I use the char data type in C++?

A char data type means a single-character type of data. It is typically used for processing text and ASCII characters.

3. What is the void data type used for in C++?

Void is used as a return type when a function does not return any value. It can also be used for unspecified pointers (e.g., void*)

4. Can the size of a float data type be changed in C++?

No, float is a fixed size in C++ (often 32 bits), and that can’t be changed. When more precision is needed, the double data type is a better option.

5. What does the bool data type store in C++?

The bool data type holds the Boolean values, which means true (1) or false (0).

About the Author

Technical Research Analyst - Full Stack Development

Kislay is a Technical Research Analyst and Full Stack Developer with expertise in crafting Mobile applications from inception to deployment. Proficient in Android development, IOS development, HTML, CSS, JavaScript, React, Angular, MySQL, and MongoDB, he’s committed to enhancing user experiences through intuitive websites and advanced mobile applications.

Full Stack Developer Course Banner