Variables in Programming
In programming, a variable is a named storage location in memory that holds a particular type of data. Variables are stored either in the memory stack or heap, and different variable types differ mainly in the size of memory they occupy.
Example in C++
#include <iostream>
int main() {
// int allows you to store values between approximately -2B to 2B
int variable = 8;
std::cout << variable << std::endl;
variable = 20;
std::cout << variable << std::endl;
std::cin.get();
}
Data Types and Their Sizes
- Int (“%d”): 32-bit integer
- Long (“%ld”): 64-bit integer
- Char (“%c”): Character type
- Float (“%f”): 32-bit real value
- Double (“%lf”): 64-bit real value
Data Type Sizes
- char: 1 byte (8 bits)
- short: 2 bytes (16 bits)
- int: 4 bytes (32 bits)
- long: 4 bytes (32 bits)
- long long: 8 bytes (64 bits)
These types can also be combined with unsigned to store only non-negative values.
Example of Floating Point Types
float var1 = 5.5f;
double var2 = 5.2;
Boolean Type
- bool: Can be
true(1) orfalse(0). Although a boolean could be represented with a single bit, it takes up one byte due to memory addressability constraints.
sizeof(bool); // Shows the size of the boolean type, which is 1 byte
Pointers and References
In addition to basic data types, C++ supports pointers and references, which are used to store memory addresses and provide indirect access to other variables.
