Stage 1: Basic Data Types in C++ - A Comprehensive Guide
A detailed discussion of data types in C++, considering memory sizes and common exam mistakes.
Foundations: Data Types in C++
Understanding how a computer stores data is crucial, especially when your solution must be efficient and memory-correct. For your exam, you need to know the specifics of each basic type.
1. Integer Types
Used to store numbers without a fractional part. Keep their ranges in mind:
int: Usually 4 bytes. The standard choice for loop counters and small numbers.short: Usually 2 bytes. Rarely used, only when memory saving is critical.long long: Minimum 8 bytes. Necessary when operating on billions (e.g., in combinatorial algorithms).
int a = 10;
long long b = 9000000000000000000LL; // Note the LL suffix2. Floating-Point Types
Used to represent real numbers. They differ in precision, which is the number of decimal digits stored accurately.
float: 4 bytes, precision approx. 7 decimal digits.double: 8 bytes, precision approx. 15-17 decimal digits. Recommended for exams to avoid rounding errors.
double pi = 3.1415926535;
float f_pi = 3.14f; // The f suffix forces the float type3. Character and Boolean Types
char: 1 byte. Stores the ASCII code of a character. Important: character literals are written in single quotes:'A'.bool: 1 byte (though it only needs 1 bit). It takestrue(1) orfalse(0).
char sign = 'X';
bool isPassed = true;The sizeof Operator
A common exam question is to check the size of a type on a given architecture. The sizeof operator is used for this.
std::cout << "Size of int: " << sizeof(int) << " bytes" << std::endl;Key Exam Pitfalls:
- Lack of Initialization: A locally declared variable (e.g.,
int x;) without an assigned value has a random value ("memory garbage"). Always writeint x = 0;. - Overflow: Adding 1 to the maximum
intvalue will cause the counter to "wrap around" to the minimum (negative) value. Uselong longif you expect huge numbers. - Division by Zero: The operation
x / 0will cause an immediate program crash. Always check the denominator before dividing.
You might also like
C++ References: Meet the 'Nicknames' of Your Variables
Understand references once and for all. How do they differ from pointers? How to use the & operator in declarations? A step-by-step guide.
Stage 11: Pointer Arithmetic in C++
Understanding how C++ operates on memory addresses. Learn why ptr++ is more than just adding one.
Stage 10: Pointers, Address-of, and Dereference Operators
Understanding the foundations of memory addressing in C++: how pointers and low-level operators work.