Topic 7 of 83
Data Types
Overview
Primitive data types define the type and size of data a variable can hold. C++ provides built-in types for integers, floating-point numbers, characters, and booleans. std::string is technically a class, but acts like a primitive for text.
Syntax
cpp
int count = 42; // Whole numbers (typically 4 bytes)
float temperature = 98.6f; // Single-precision floating point (4 bytes)
double precise = 3.14159; // Double-precision floating point (8 bytes)
char grade = 'A'; // Single character (1 byte)
bool isOnline = true; // Boolean true/false (1 byte)
std::string name = "John"; // Text (from <string> library)Common Pitfalls
- Forgetting the 'f' suffix on float literals (e.g., `float f = 3.14;` creates a double and converts it to float).
Interview Tips
- Know that the exact size of primitives (like int) depends on the compiler and architecture, but you can check it using `sizeof(int)`.
- Understand why comparing floating-point numbers directly (e.g., a == b) is dangerous due to precision issues.
Real-World Example
Checking the size of data types in memory.
example
cpp
#include <iostream>
using namespace std;
int main() {
cout << "Size of int: " << sizeof(int) << " bytes\n";
cout << "Size of double: " << sizeof(double) << " bytes\n";
return 0;
}