Data Types in C++
In C++, data types are essential for defining variables that store different kinds of values. When a variable is declared, memory is allocated based on its data type. C++ offers a combination of primitive (built-in) data types and allows the creation of user-defined types. Here’s a detailed breakdown of the types:
1. Primitive Built-in Types:
Type | Keyword | Description |
---|---|---|
Boolean | bool | Stores true or false values. |
Character | char | Stores a single character (1 byte). |
Wide Character | wchar_t | Stores a larger set of characters (2 or 4 bytes). |
Integer | int | Stores whole numbers. |
Floating Point | float | Stores single-precision decimal numbers. |
Double Precision | double | Stores double-precision decimal numbers. |
Valueless | void | Used to indicate no value. |
2. Type Modifiers:
Some basic types can be modified using the following type modifiers:
signed
: Ensures the data type can store both negative and positive values.unsigned
: Restricts the data type to only store positive values, thus expanding its range.short
: Reduces the storage size (applies to integers).long
: Increases the storage size (applies to integers and doubles).
3. Memory Allocation and Ranges:
Data Type | Size | Range |
---|---|---|
char | 1 byte | -127 to 127 (signed) or 0 to 255 (unsigned) |
int | 4 bytes | -2,147,483,648 to 2,147,483,647 |
unsigned int | 4 bytes | 0 to 4,294,967,295 |
short int | 2 bytes | -32,768 to 32,767 |
unsigned short int | 2 bytes | 0 to 65,535 |
long int | 4 bytes | -2,147,483,647 to 2,147,483,647 |
float | 4 bytes | ±3.4e±38 (~7 digits precision) |
double | 8 bytes | ±1.7e±308 (~15 digits precision) |
long double | 8 bytes | Similar to double , more precision |
wchar_t | 2 or 4 bytes | Represents wide characters |
4. Example Program to Check Data Type Sizes:
This program will output the size of various data types based on the system/compiler being used.
5. typedef
Declarations:
typedef
is used to create an alias for an existing type, which makes code more readable. The syntax is:
typedef existing_type new_name;
6. Enumerated Types:
An enumeration allows the definition of a set of named integer constants. Enumerated types are defined using the enum
keyword:
enum color { red, green, blue };
color c = blue; // Assigning enumerated value to variable
0
, the second 1
, and so on.enum color { red, green = 5, blue }; // green = 5, blue = 6
Summary:
C++ offers a diverse range of data types that provide flexibility in storing various types of information. The use of built-in types along with modifiers allows programmers to effectively manage memory while ensuring proper data storage. Data types like enum
and typedef
further enhance readability and make code easier to maintain.
No comments:
Post a Comment