c++-data-types

“`html

Do you believe you are skilled in C++ data types? Reconsider. Utilizing the incorrect built-in type, even a seemingly straightforward choice like int versus double, can covertly disrupt your code. C++ offers fundamental data types to manage different categories of data. There are three classifications for those types, including Primitive (Built-in) Types, Derived Data Types, and User-Defined Data Types. Modifiers and sophisticated elements like typedef and enumerations also augment them.

In this article, we will explore all C++ data types, complete with illustrative codes, performance recommendations, and practical applications, enabling you to code in a more organized, swift, and dependable manner. Don’t let a basic data type lead you into a concealed bug.

Table of Contents:

What are Data Types in C++?

In C++, data types denote the nature of data a variable is capable of holding, such as int, float, bool, char, etc. These data types assist the compiler in allocating the proper amount of memory and executing suitable modifications.

Categories of Data Types

There are 3 categories of data:

  1. Primitive data types
  2. Derived data types
  3. User-defined data types

1. Primitive Built-in Types in C++

C++ encompasses primitive built-in types, which are the most essential data types. The compiler supplies these built-in data types to create variables and represent basic values. Some of the primitive types include: int (integer), float and double (decimal or floating-point), char (individual character), bool (truth value), void (the non-value primarily utilized in functions that yield no output), etc. These are fundamental types required for arithmetic, decision-making, and program control flow. They form the foundation for advanced data structures and custom types.

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

Now let’s delve deeper into these data types:

1. int (Integer Type)

The int data type is designed to store whole numbers, i.e., (or integer type), including both positive and negative values without fractional components.

Example:

Cpp

Code Copied!

var isMobile = window.innerWidth “);

editor28510.setValue(decodedContent); // Set the default text editor28510.clearSelection();

editor28510.setOptions({ maxLines: Infinity });

function decodeHTML28510(input) { var doc = new DOMParser().parseFromString(input, “text/html”); return doc.documentElement.textContent; }

// Function to copy code to clipboard function copyCodeToClipboard28510() { const code = editor28510.getValue(); // Get code from the editor navigator.clipboard.writeText(code).then(() => { // alert(“Code copied to clipboard!”);

jQuery(“.maineditor28510 .copymessage”).show(); setTimeout(function() { jQuery(“.maineditor28510 .copymessage”).hide(); }, 2000); }).catch(err => { console.error(“Error copying code: “, err); }); }

function runCode28510() {

var code = editor28510.getSession().getValue();

jQuery(“#runBtn28510 i.run-code”).show(); jQuery(“.output-tab”).click();

jQuery.ajax({ url: “https://intellipaat.com/blog/wp-admin/admin-ajax.php”, type: “post”,

data: { language: “cpp”, code: code, cmd_line_args: “”, variablenames: “”, action:”compilerajax” }, success: function(response) { var myArray = response.split(“~”); var data = myArray[1];

jQuery(“.output28510”).html(“

"+data+"");
									jQuery(".maineditor28510
``````html
.code-editor-output").show();
									jQuery("#runBtn28510 i.run-code").hide();
									
								}
							})
					

						}
						
						
		function closeoutput28510() {	
		var code = editor28510.getSession().getValue();
		jQuery(".maineditor28510 .code-editor-output").hide();
		}

    // Bind event listeners to the buttons
    document.getElementById("copyBtn28510").addEventListener("click", copyCodeToClipboard28510);
    document.getElementById("runBtn28510").addEventListener("click", runCode28510);
    document.getElementById("closeoutputBtn28510").addEventListener("click", closeoutput28510);
 
    



Result: 

datatype-int

The above C++ program initializes an integer variable age with a value of 25, allowing the use of cout in C++ to output this value.

2. float (Floating Point Type)

The float data type denotes decimal numbers in single precision real numbers, which are those that may possess a fractional component but are less precise than double. Float is typically employed when memory usage is of minimal concern. It occupies 32 bits of memory and can represent a minimum of 1.5 × 10^−45 and a maximum of 3.4 × 10^38.

Sample: 

Cpp
Code Copied!

Result:

datatype-float

The code provided initializes a variable called temperature with a float value of 36.6f, and the cout line outputs the current temperature value on the console as “Temperature: 36.6”. Finally, the program returns 0, signaling successful completion.

3. double (Double Precision Type)

A decimal number is represented in double precision, which indicates that the double data type offers greater accuracy than float. Double is a 64-bit type, allowing it to accommodate a broader range of values and to represent all values more effectively. Double is preferred for calculations needing specific precision.

Sample: 

Cpp
Code Copied!

Output:

datatype-double

The snippet above illustrates the implementation of double in C++. Here, the variable pi is declared and initialized to the value of 3.1415926535. Even though the double offers double precision, it can accommodate a greater number of decimal points compared to a float. Utilizing cout, the application displays the pi values and concludes by returning 0.

4. char (Character Type)

Char holds a single character enclosed in single quotes '‘ ‘; It can consist of letters, numbers, or various symbols, and is preserved as an integer value based on ASCII. This indicates that the character 'A' would be stored in memory as 65. Although the char data type is a 1-byte data type, it is frequently used for characters in strings as well as for user input and displaying output.

Example:

Cpp
Code Copied!
``````javascript document.getElementById("copyBtn20748").addEventListener("click", copyCodeToClipboard20748); document.getElementById("runBtn20748").addEventListener("click", runCode20748); document.getElementById("closeoutputBtn20748").addEventListener("click", closeoutput20748);

Output: 

datatype-char

The code presented above illustrates the char data type in C++. A variable called grade is initialized with the character ‘A’, which retains the single character in its memory. The cout command outputs the value of the grade. 

5. bool (Boolean Type)

Bool holds a boolean value:

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

Boolean is utilized for decision-making in conditional expressions such as if, while, if-else, and loops. 

Example:

Cpp
Code Copied!

Output: 

datatype-bool

The code above illustrates the bool declaration in C++. A variable named isPassed is initialized to true, which indicates a logical “yes” or successful execution. In memory, the true value is retained as 1. The cout command then displays this stored value on the console. A program concluding with a return 0 signifies a successful execution. 

6. void (Empty Type)

Void signifies no value and is utilized when a function does not return any value. It indicates to the compiler that the function carries out a process without yielding a value to the user. The void type is also applicable for pointers when the data type is unspecified (void*). It’s essential for functions designed to execute without returning any output to the script.

Example: 

Cpp
Code Copied!

Output: 

datatype-void

The code illustrated above showcases the void return type in a function. The function greet(), defined with the void specifier, does not return a value. It merely prints the “Hello world!” inside that function, sending it to the console. In the main method, we invoke greet(), which executes the print statement. Ultimately, the program concludes with a return 0, indicating successful execution.

7. Wide Character 

Wide characters are utilized for more extensive sets that cannot be portrayed by standard character types (which are 1 byte and ASCII-based). In C++, wide characters are represented using the wchar_t type, which can store Unicode or other multi-byte character sets.

They are referred to as “wide” characters and are beneficial for internationalization, Unicode characters, and languages with significant alphabets such as Chinese and Japanese.

Example: 

Cpp
Code Copied!
``````html document.getElementById("runBtn5127").addEventListener("click", runCode5127); document.getElementById("closeoutputBtn5127").addEventListener("click", closeoutput5127);

Outcome:

datatype-wide-character

The example above of a C++ program illustrates the application of wide characters and wide strings utilizing wchar_t and wstring. The symbol ‘あ’ (Japanese Hiragana) and wide literals are identified by the L prefix. Rather than cout, you utilize wcout to correctly output wide characters. This allows the program to handle and display Unicode characters such as emojis and non-ASCII text.

2. Derived Data Types in C++

In C++, the derived data types are the categories that are formed from the basic data types. The derived data types encompass types such as arrays, functions, pointers, and references. These data types are effective for data management and manipulation.

1. Array

An array constitutes a collection or set of elements of the identical type retained in consecutive memory locations. Arrays are employed when numerous values of the same type need to be retained and accessed via an index.

Illustration:

Cpp
Code Copied!

Outcome:

datatype-array

The subsequent program illustrates the use of an array in C++. Here, an integer type array is defined with the identifier numbers, consisting of 3 elements: 10, 20, and 30. Arrays are utilized to retain multiple values of the same type in a single variable. Then the program accesses and displays the first element of the array, utilizing 0 as an index. Using cout, the  “First number: 10” is shown. The program concludes with a return 0, signifying successful execution.

2. Pointer

A pointer is a variable that stores the memory address of another variable. Pointers are potent and advantageous in dynamic memory allocation, arrays, and functions.

Illustration:

Cpp
Code Copied!

Output:

typedef-pointer

In C++, we utilized a pointer to execute this program by assigning num = 42. Next, declare a pointer ptr to hold the address of num using the & operator. In this scenario, we apply the *ptr expression to dereference the pointer, enabling us to access the value stored at that memory address. The output of the program is: Value using pointer: 42.

3. Function

Functions are reusable segments within code that take parameters and return values.

Example:

Cpp
Code Copied!

Output:

``````html
datatype-function

The prior code illustrates the declaration of functions in C++. In this case, the add function is defined to accept two integers, a and b. Within the main function, the add(5, 10) call computes the result of 15. This outcome is displayed using cout, yielding the output as Sum: 15.

4. Reference

In C++, a reference variable acts as an alternative name for an already existing variable. References are utilized to hold memory addresses, akin to pointers. A reference is designated with an ampersand (&) right beside the type.

Syntax:

type& reference_name = existing_variable;

(&) denotes the reference, whereas type defines the data type (int, float, string) of the variable being referenced, reference_name indicates the name of the reference, and existing_variable is the variable that the reference is pointing to.

Example:

Cpp

Code Copied!

var isMobile = window.innerWidth ");

editor8656.setValue(decodedContent); editor8656.clearSelection();

editor8656.setOptions({ maxLines: Infinity });

function decodeHTML8656(input) { var doc = new DOMParser().parseFromString(input, "text/html"); return doc.documentElement.textContent; }

function copyCodeToClipboard8656() { const code = editor8656.getValue(); navigator.clipboard.writeText(code).then(() => { jQuery(".maineditor8656 .copymessage").show(); setTimeout(function() { jQuery(".maineditor8656 .copymessage").hide(); }, 2000); }).catch(err => { console.error("Error copying code: ", err); }); }

function runCode8656() { var code = editor8656.getSession().getValue(); jQuery("#runBtn8656 i.run-code").show(); jQuery(".output-tab").click();

jQuery.ajax({ url: "https://intellipaat.com/blog/wp-admin/admin-ajax.php", type: "post", data: { language: "cpp", code: code, cmd_line_args: "", variablenames: "", action:"compilerajax" }, success: function(response) { var myArray = response.split("~"); var data = myArray[1]; jQuery(".output8656").html("

"+data+"

"); jQuery(".maineditor8656 .code-editor-output").show(); jQuery("#runBtn8656 i.run-code").hide(); } }); }

function closeoutput8656() { jQuery(".maineditor8656 .code-editor-output").hide(); }

document.getElementById("copyBtn8656").addEventListener("click", copyCodeToClipboard8656); document.getElementById("runBtn8656").addEventListener("click", runCode8656); document.getElementById("closeoutputBtn8656").addEventListener("click", closeoutput8656);

Output:

datatype - reference

In this instance, num is an integer variable initialized with the value of 7, while ref signifies the memory location of that variable. In the preceding code, altering the value of ref also alters the value of num.

3. User-Defined Data Types in C++

In C++, user-defined data types are generated by the programmers, enabling them to construct their own data structures based on the built-in types. These custom data types, such as struct, union, class, and enum, facilitate the structuring of complex data.

1. Struct

A struct (short for structured) is a method to combine multiple variables of varying types under a single name, simplifying their management as one cohesive entity. This is particularly advantageous when we aim to represent entities with various attributes, such as a student, an employee, or a book. By default, all members of a struct are public and can be accessed using the dot (.) operator. Structs improve the readability of code when handling complex data.

Example:

Cpp

Code Copied!

``````html

var isMobile = window.innerWidth "");

editor73915.setValue(decodedContent); // Establish the default text editor73915.clearSelection();

editor73915.setOptions({ maxLines: Infinity });

function decodeHTML73915(input) { var doc = new DOMParser().parseFromString(input, "text/html"); return doc.documentElement.textContent; }

// Function to duplicate code to clipboard function copyCodeToClipboard73915() { const code = editor73915.getValue(); // Retrieve code from the editor navigator.clipboard.writeText(code).then(() => { // alert("Code copied to clipboard!"); jQuery(".maineditor73915 .copymessage").show(); setTimeout(function() { jQuery(".maineditor73915 .copymessage").hide(); }, 2000); }).catch(err => { console.error("Error duplicating code: ", err); }); }

function runCode73915() { var code = editor73915.getSession().getValue();

jQuery("#runBtn73915 i.run-code").show(); jQuery(".output-tab").click();

jQuery.ajax({ url: "https://intellipaat.com/blog/wp-admin/admin-ajax.php", type: "post", data: { language: "cpp", code: code, cmd_line_args: "", variablenames: "", action: "compilerajax" }, success: function(response) { var myArray = response.split("~"); var data = myArray[1];

jQuery(".output73915").html("

" + data + "

"); jQuery(".maineditor73915 .code-editor-output").show(); jQuery("#runBtn73915 i.run-code").hide(); } }); }

function closeoutput73915() { var code = editor73915.getSession().getValue(); jQuery(".maineditor73915 .code-editor-output").hide(); }

// Link event listeners to the buttons document.getElementById("copyBtn73915").addEventListener("click", copyCodeToClipboard73915); document.getElementById("runBtn73915").addEventListener("click", runCode73915); document.getElementById("closeoutputBtn73915").addEventListener("click", closeoutput73915);

Output:

datatype-struct

The code above illustrates the definition of a struct. Here we define Student as a struct, which includes a Student ID and a Student grade. The student ID is assigned as an Integer, and the student grade is set as a char. By creating the instance s1, we can access its members using the dot operator.

2. union

A union resembles a struct, but unlike a struct, it utilizes shared memory for all its members. This means all members of a union occupy the same memory space, with only one member holding a value at any time. Thus, assigning a new value to one member replaces the existing one; unions are efficient in memory usage when only one member is required at a time. Hence, unions are advantageous where memory optimization is essential & typically used in embedded systems or low-level programming.

Example:

Cpp

Code Duplicated!

var isMobile = window.innerWidth "");

editor14973.setValue(decodedContent); // Establish the default text editor14973.clearSelection();

editor14973.setOptions({ maxLines: Infinity });

function decodeHTML14973(input) { var doc = new DOMParser().parseFromString(input, "text/html"); return doc.documentElement.textContent; }

// Function to duplicate code to clipboard function copyCodeToClipboard14973() { const code = editor14973.getValue(); // Retrieve code from the editor navigator.clipboard.writeText(code).then(() => { // alert("Code duplicated to clipboard!"); jQuery(".maineditor14973 .copymessage").show(); setTimeout(function() { jQuery(".maineditor14973 .copymessage").hide(); }, 2000); }).catch(err => { console.error("Error duplicating code: ", err); }); }

function runCode14973() { var code = editor14973.getSession().getValue();

jQuery("#runBtn14973 i.run-code").show(); jQuery(".output-tab").click();

jQuery.ajax({ url: "https://intellipaat.com/blog/wp-admin/admin-ajax.php", type: "post", data: { language: "cpp", code: code, cmd_line_args: "", variablenames: "", action: "compilerajax" }, success: function(response) { var myArray = response.split("~"); var data = myArray[1];

jQuery(".output14973").html("

" + data + "

"); jQuery(".maineditor14973 .code-editor-output").show(); jQuery("#runBtn14973 i.run-code").hide(); } }); } ``````html { var myArray = response.split("~"); var data = myArray[1];

jQuery(".output14973").html("

"+data+"");
    jQuery(".maineditor14973 .code-editor-output").show();
    jQuery("#runBtn14973 i.run-code").hide();
}

function closeoutput14973() { var code = editor14973.getSession().getValue(); jQuery(".maineditor14973 .code-editor-output").hide(); }

// Bind event listeners to the buttons document.getElementById("copyBtn14973").addEventListener("click", copyCodeToClipboard14973); document.getElementById("runBtn14973").addEventListener("click", runCode14973); document.getElementById("closeoutputBtn14973").addEventListener("click", closeoutput14973);

Output:

data type-union

The preceding C++ example illustrates a union. As noted, the union Data comprises two members – an integer i and a float f, both sharing the same memory space. Initially, i is set to 10; thus, the output displays “Integer: 10”. Subsequently, when we assign f a value of 3.14, it overwrites the former value held in i, resulting in the output “Float: 3.14,” indicating that the union retains only one value at any given time.

3. Class

A class is similar to a struct, yet its members are private by default. It also enables encapsulation, meaning data is modified or accessed solely through its public methods. Classes serve as blueprints for objects, playing a vital role in object-oriented programming (OOP).

Example:

Cpp

Code Copied!

var isMobile = window.innerWidth ");

editor2416.setValue(decodedContent); // Set the default text editor2416.clearSelection();

editor2416.setOptions({ maxLines: Infinity });

function decodeHTML2416(input) { var doc = new DOMParser().parseFromString(input, "text/html"); return doc.documentElement.textContent; }

// Function to copy code to clipboard function copyCodeToClipboard2416() { const code = editor2416.getValue(); // Get code from the editor navigator.clipboard.writeText(code).then(() => { jQuery(".maineditor2416 .copymessage").show(); setTimeout(function () { jQuery(".maineditor2416 .copymessage").hide(); }, 2000); }).catch(err => { console.error("Error copying code: ", err); }); }

function runCode2416() { var code = editor2416.getSession().getValue();

jQuery("#runBtn2416 i.run-code").show(); jQuery(".output-tab").click();

jQuery.ajax({ url: "https://intellipaat.com/blog/wp-admin/admin-ajax.php", type: "post", data: { language: "cpp", code: code, cmd_line_args: "", variablenames: "", action: "compilerajax" }, success: function (response) { var myArray = response.split("~"); var data = myArray[1];

jQuery(".output2416").html("

"+data+"");
            jQuery(".maineditor2416 .code-editor-output").show();
            jQuery("#runBtn2416 i.run-code").hide();
        }
    })
}

function closeoutput2416() { var code = editor2416.getSession().getValue(); jQuery(".maineditor2416 .code-editor-output").hide(); }

// Bind event listeners to the buttons document.getElementById("copyBtn2416").addEventListener("click", copyCodeToClipboard2416); document.getElementById("runBtn2416").addEventListener("click", runCode2416); document.getElementById("closeoutputBtn2416").addEventListener("click", closeoutput2416);

Output:

data types-class

This example illustrates a class Car that possesses a public variable named brand, along with a method display() that outputs the brand. Within the main function, the Car class instantiates an object c1, where the brand is assigned the value “Toyota”, and the display method is invoked, resulting in the output: Brand: Toyota.

4. enum (Enumeration)

To enhance code clarity, the enum establishes a collection of named integer constants.

Example:

Cpp

Code Copied!

``````html
Dismiss Code

var isMobile = window.innerWidth ");

editor13304.setValue(decodedContent); // Establish the preset text editor13304.clearSelection();

editor13304.setOptions({ maxLines: Infinity });

function decodeHTML13304(input) { var doc = new DOMParser().parseFromString(input, "text/html"); return doc.documentElement.textContent; }

// Function to copy code to clipboard function copyCodeToClipboard13304() { const code = editor13304.getValue(); // Extract code from the editor navigator.clipboard.writeText(code).then(() => { // alert("Code copied to clipboard!");

jQuery(".maineditor13304 .copymessage").show(); setTimeout(function() { jQuery(".maineditor13304 .copymessage").hide(); }, 2000); }).catch(err => { console.error("Error copying code: ", err); }); }

function runCode13304() {

var code = editor13304.getSession().getValue();

jQuery("#runBtn13304 i.run-code").show(); jQuery(".output-tab").click();

jQuery.ajax({ url: "https://intellipaat.com/blog/wp-admin/admin-ajax.php", type: "post",

data: { language: "cpp", code: code, cmd_line_args: "", variablenames: "", action:"compilerajax" }, success: function(response) { var myArray = response.split("~"); var data = myArray[1];

jQuery(".output13304").html("

"+data+"");
									jQuery(".maineditor13304 .code-editor-output").show();
									jQuery("#runBtn13304 i.run-code").hide();

} })

}

function closeoutput13304() { var code = editor13304.getSession().getValue(); jQuery(".maineditor13304 .code-editor-output").hide(); }

// Assign event listeners to the buttons document.getElementById("copyBtn13304").addEventListener("click", copyCodeToClipboard13304); document.getElementById("runBtn13304").addEventListener("click", runCode13304); document.getElementById("closeoutputBtn13304").addEventListener("click", closeoutput13304);

Result: 

data types-enum

In the preceding code, the enum day is established, assigning values starting from 0 (sun = 0, mon = 1,…). The current day is defined as Monday, resulting in an output of 1. 

5. Typedef Established Data Type

Typedef in C++ is employed to create a new designation (alias) for another data type. This enhances code clarity and simplifies type modifications in extensive programs. To achieve this, the keyword typedef is utilized.

example:

Cpp

Code Duplicated!

var isMobile = window.innerWidth ");

editor87497.setValue(decodedContent); // Establish the preset text editor87497.clearSelection();

editor87497.setOptions({ maxLines: Infinity });

function decodeHTML87497(input) { var doc = new DOMParser().parseFromString(input, "text/html"); return doc.documentElement.textContent; }

// Function to copy code to clipboard function copyCodeToClipboard87497() { const code = editor87497.getValue(); // Extract code from the editor navigator.clipboard.writeText(code).then(() => { // alert("Code copied to clipboard!");

jQuery(".maineditor87497 .copymessage").show(); setTimeout(function() { jQuery(".maineditor87497 .copymessage").hide(); }, 2000); }).catch(err => { console.error("Error copying code: ", err); }); }

function runCode87497() {

var code = editor87497.getSession().getValue();

jQuery("#runBtn87497 i.run-code").show(); jQuery(".output-tab").click();

jQuery.ajax({ url: "https://intellipaat.com/blog/wp-admin/admin-ajax.php", type: "post",

data: { language: "cpp", code: code, cmd_line_args: "", variablenames: "", action:"compilerajax" }, success: function(response) { var myArray = response.split("~"); var data = myArray[1];

jQuery(".output87497").html("

"+data+"");
									jQuery(".maineditor87497 .code-editor-output").show();
									jQuery("#runBtn87497 i.run-code").hide();

} })

}

function closeoutput87497() { var code = editor87497.getSession().getValue(); jQuery(".maineditor87497 .code-editor-output").hide(); }

// Assign event listeners to the buttons document.getElementById("copyBtn87497").addEventListener("click", ``````javascript copyCodeToClipboard87497); document.getElementById("runBtn87497").addEventListener("click", runCode87497); document.getElementById("closeoutputBtn87497").addEventListener("click", closeoutput87497);

Outcome:

Data types-typedef

This typedef designates  uint as an unsigned integer. This improves the clarity of the code and facilitates management, particularly when  employing intricate types repeatedly.

Summary

In C++, data types can be classified into three groups: Primitive Built-in Data Types, Derived Data Types, and User-Defined Data  Types. Basic elements (such as int,  float, char) and derived elements (array, pointer, function) form the foundation of the language. User-defined Types enable developers to construct custom data structures like classes, structs, unions, enums, etc. Grasping the significance of  these various data types aids in structuring and maximizing data in a program. Familiarity with  these categories is essential for producing well-structured and accurate C++ code.

For additional insights on C++, visit the C++ article, and also check out C++ Interview Questions curated by industry professionals.

C++ Data Types – FAQs

1. What distinguishes int from double in C++?

The int data type allows only whole numbers without decimals. Conversely, double signifies floating-point numbers that necessitate high precision with decimal values.

2. When is it appropriate to utilize the char data type in C++?

A char data type represents a single-character type of information. It is generally employed for handling text and ASCII characters.

3. What purpose does the void data type serve in C++?

Void acts as a return type for functions that do not return a value. It can also be used for unspecified pointers (e.g., void*)

4. Is it possible to alter the size of a float data type in C++?

No, float is a fixed size in C++ (typically 32 bits), which cannot be modified. When enhanced precision is required, the double data type is a preferable alternative.

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

The bool data type stores Boolean values, indicating true (1) or false (0).

The article C++ Data Types first appeared on Intellipaat Blog.

```


Leave a Reply

Your email address will not be published. Required fields are marked *

Share This