C++ Data Types & Constants
Primitive Data Types:
Integer Types:
int: Integer type (typically 4 bytes on most systems).
short: Short integer (usually 2 bytes).
long: Long integer (at least 4 bytes).
long long: Long long integer (at least 8 bytes).
Example:
int num = 42;
Floating-Point Types:
float: Single-precision floating-point (4 bytes).
double: Double-precision floating-point (8 bytes).
long double: Extended precision floating-point.
Example:
double pi = 3.14;
Character Types:
char: Single character (1 byte).
wchar_t: Wide character (platform-dependent size).
Example:
char grade = 'A';
Boolean Type:
bool: Represents true or false.
Example:
bool isSunny = true;
Derived Data Types:
Array:
A collection of elements of the same data type.
Example:
int numbers[5] = {1, 2, 3, 4, 5};
Pointer:
Stores the memory address of another variable.
Example:
int* ptr = #
Reference:
An alias to an existing variable.
Example:
int& ref = num;
User-Defined Data Types:
Struct:
Groups variables of different data types under a single name.
Example:
struct Point {
int x;
int y;
};
Class:
Similar to a struct but with the ability to include member functions.
Example:
class Rectangle {
public:
int length;
int width;
int area() { return length * width; }
};
Type Modifiers:
const:
Used to define constants.
Example:
const double PI = 3.14159;
unsigned:
Used with integer types to represent only non-negative values.
Example:
unsigned int count = 10;
signed:
Used with integer types to represent both positive and negative values (default).
Example:
signed int temperature = -5;
Type Inference (C++11 and later):
auto:
Allows the compiler to deduce the variable's data type.
Example:
auto speed = 55.5; // Compiler infers speed as a double
These are the basic data types in C++. Understanding their usage, limitations, and interactions is crucial for effective programming. Constants are also an important concept, and you can use the const keyword to define them. Constants cannot be modified once they are assigned a value.
const int MAX_VALUE = 100;
These are the foundational data types in C++. As you advance in your programming journey, you'll encounter more advanced data types and structures provided by libraries and frameworks, as well as those you create yourself.