Variables_datatypes
Variables and Data Types
Section titled “Variables and Data Types”Variables are the foundation of any program. They store data that your program can manipulate. In this chapter, you’ll learn about the different data types in C++, how to declare and use variables, and important concepts like type safety and conversion.
What is a Variable?
Section titled “What is a Variable?”A variable is a named storage location in memory that holds a value. Think of it as a labeled box where you can store and retrieve data.
┌─────────────────────┐│ Variable ││ ┌───────────────┐ ││ │ myValue │ ││ │ 42 │ ││ └───────────────┘ ││ ↑ name ││ ↑ value ││ ↑ type │└─────────────────────┘Declaring Variables
Section titled “Declaring Variables”In C++, you must declare a variable before using it:
// Basic declarationint age;double price;char grade;
// Declaration with initializationint count = 10;std::string name = "John";
// Multiple declarationsint a, b, c;int x = 1, y = 2, z = 3;Data Types Overview
Section titled “Data Types Overview”C++ provides several fundamental data types:
┌─────────────────────────────────────────────────────────────┐│ C++ Data Types │├─────────────────────────────────────────────────────────────┤│ Primary Types ││ ├── Integer → int, short, long, long long ││ ├── Float → float, double, long double ││ ├── Character → char, wchar_t, char16_t, char32_t ││ ├── Boolean → bool ││ └── Void → void │├─────────────────────────────────────────────────────────────┤│ Derived Types ││ ├── Pointer → int* ││ ├── Reference → int& ││ ├── Array → int[] ││ ├── Function → void func() ││ └── Class → class, struct, union │└─────────────────────────────────────────────────────────────┘Integer Types
Section titled “Integer Types”Integer types represent whole numbers.
| Type | Typical Size | Typical Range |
|---|---|---|
short | 2 bytes | -32,768 to 32,767 |
int | 4 bytes | -2,147,483,648 to 2,147,483,647 |
long | 4 or 8 bytes | Platform dependent |
long long | 8 bytes | Very large numbers |
Signed vs Unsigned
Section titled “Signed vs Unsigned”// Signed (can be negative) - defaultint signedInt = -10;
// Unsigned (only positive)unsigned int unsignedInt = 10;unsigned short ushortVar = 100;unsigned long ulongVar = 1000;Integer Constants
Section titled “Integer Constants”// Decimal (base 10)int decimal = 42;
// Octal (base 8) - starts with 0int octal = 052;
// Hexadecimal (base 16) - starts with 0xint hex = 0x2A;
// Binary (C++14) - starts with 0bint binary = 0b101010;
// With suffixlong long bigNum = 123456789LL; // long long suffixunsigned int posNum = 42U; // unsigned suffixSize of Types
Section titled “Size of Types”Use sizeof to find the size of any type:
#include <iostream>
int main() { std::cout << "Size of int: " << sizeof(int) << " bytes" << std::endl; std::cout << "Size of long: " << sizeof(long) << " bytes" << std::endl; std::cout << "Size of double: " << sizeof(double) << " bytes" << std::endl; std::cout << "Size of char: " << sizeof(char) << " bytes" << std::endl;
return 0;}Floating-Point Types
Section titled “Floating-Point Types”Floating-point types represent numbers with decimal parts.
| Type | Precision | Typical Size |
|---|---|---|
float | ~6-7 digits | 4 bytes |
double | ~15 digits | 8 bytes |
long double | ~18 digits | 16 bytes (often) |
Floating-Point Constants
Section titled “Floating-Point Constants”// Without suffix - double by defaultdouble d1 = 3.14;
// Float suffixfloat f1 = 3.14f;float f2 = 3.14F;
// Long double suffixlong double ld1 = 3.14L;
// Scientific notationdouble big = 1.5e10; // 1.5 × 10^10double small = 1.5e-5; // 1.5 × 10^-5Precision Example
Section titled “Precision Example”#include <iostream>#include <iomanip>
int main() { float f = 3.14159265358979323846; double d = 3.14159265358979323846; long double ld = 3.14159265358979323846;
std::cout << std::setprecision(20); std::cout << "float: " << f << std::endl; std::cout << "double: " << d << std::endl; std::cout << "long double: " << ld << std::endl;
return 0;}Character Types
Section titled “Character Types”Character types store single characters.
| Type | Description |
|---|---|
char | At least 8 bits (1 byte) |
wchar_t | Wide character (platform dependent) |
char16_t | 16-bit Unicode (C++11) |
char32_t | 32-bit Unicode (C++11) |
Character Examples
Section titled “Character Examples”// Character literals (single quotes)char c1 = 'A';char c2 = '9';char c3 = '$';
// Escape sequenceschar newline = '\n';char tab = '\t';char backslash = '\\';char quote = '\"';
// ASCII valueschar a = 65; // 'A'std::cout << a << std::endl; // Prints 'A'
// Wide characters (for Unicode)wchar_t w = L'Ω';Boolean Type
Section titled “Boolean Type”The boolean type represents true or false values.
bool isActive = true;bool isComplete = false;
// Boolean from comparisonsint x = 10;bool isPositive = (x > 0); // truebool isEven = (x % 2 == 0); // true
// Boolean in conditionsif (isActive) { // Do something}Boolean Behavior
Section titled “Boolean Behavior”In C++, any value can be converted to bool:
0converts tofalse- Non-zero values convert to
true
bool b1 = 0; // falsebool b2 = 42; // truebool b3 = -1; // true (non-zero)bool b4 = nullptr; // falseVoid Type
Section titled “Void Type”The void type represents “no type” or “no value”.
// Function that returns nothingvoid greet() { std::cout << "Hello!" << std::endl;}
// Function that takes no parametersvoid process(void); // C-style, avoid in modern C++
// Generic pointer (avoid in modern C++)void* ptr;Type Modifiers
Section titled “Type Modifiers”C++ provides modifiers to alter the meaning of base types:
Makes a variable read-only:
const int MAX_SIZE = 100;int const MAX_VALUE = 50; // Also valid, less common
// MAX_SIZE = 200; // ERROR: Cannot modify const
// const with pointersconst int* p1; // Pointer to const intint const* p2; // Same as aboveint* const p3; // Const pointer to intconst int* const p4; // Const pointer to const intconstexpr (C++11)
Section titled “constexpr (C++11)”Compile-time constant expression:
constexpr int SIZE = 100; // Computed at compile timeconstexpr int SQUARED(int x) { // Compile-time function return x * x;}
int arr[SQUARED(5)]; // Array of size 25static
Section titled “static”Makes a variable have static storage duration:
void function() { static int count = 0; // Initialized once, retains value count++; std::cout << count << std::endl;}
int main() { function(); // prints 1 function(); // prints 2 function(); // prints 3}extern
Section titled “extern”Declares a variable defined elsewhere:
int globalVar = 42;
// file2.cppextern int globalVar;std::cout << globalVar << std::endl; // prints 42Type Aliases
Section titled “Type Aliases”Create alternative names for types using typedef (legacy) or using (modern):
// C++11 using (preferred)using IntPtr = int*;using Matrix = std::vector<std::vector<int>>;using Callback = void(*)(int);
// Legacy typedeftypedef int* IntPtr;typedef void (*Callback)(int);Type Deduction (auto)
Section titled “Type Deduction (auto)”C++11 introduced auto for automatic type deduction:
auto i = 42; // intauto d = 3.14; // doubleauto s = "hello"; // const char*auto sum = 1 + 2.0; // double
// With iterators (very useful)auto it = vec.begin(); // std::vector<int>::iterator
// Function return typeauto add(int a, int b) -> int { return a + b;}Type Conversions
Section titled “Type Conversions”Implicit Conversion (Automatic)
Section titled “Implicit Conversion (Automatic)”C++ automatically converts between compatible types:
int i = 42;double d = i; // int → double (implicit)int j = d; // double → int (implicit, truncates!)
char c = 'A';int x = c; // char → int (ASCII value 65)Explicit Conversion (Casting)
Section titled “Explicit Conversion (Casting)”double d = 3.99;
// C-style cast (avoid in C++)int i = (int)d; // 3
// C++ casts (preferred)int i1 = static_cast<int>(d); // 3int i2 = reinterpret_cast<int>(&d); // pointer to int
// const cast (avoid)const int ci = 42;int* pi = const_cast<int*>(&ci);Numeric Promotions
Section titled “Numeric Promotions”// Integer promotionschar c = 'A';int i = c; // char → int
// Float to doublefloat f = 3.14f;double d = f; // float → doubleInitialization Methods
Section titled “Initialization Methods”C++ provides multiple ways to initialize variables:
int a = 10; // Copy initializationint b(20); // Direct initializationint c{30}; // Brace initialization (preferred)int d = {}; // Zero initializationint e{}; // Zero initialization (preferred in modern C++)Why Brace Initialization?
Section titled “Why Brace Initialization?”// Prevents narrowing conversionsint x1{10}; // OKint x2{10.5}; // ERROR: narrowing conversion
int y1 = 10; // OKint y2 = 10.5; // OK: compiles but truncates (dangerous!)
// Works with containersstd::vector<int> v{1, 2, 3}; // Initializes with 3 elementsVariables Scope
Section titled “Variables Scope”Variables have different lifetimes depending on where they’re declared:
// Global variableint globalVar = 100;
int main() { // Local variable int localVar = 10;
// Block scope { int blockVar = 20; std::cout << globalVar << localVar << blockVar; } // blockVar is not accessible here
return 0;}Best Practices
Section titled “Best Practices”1. Always Initialize Variables
Section titled “1. Always Initialize Variables”// Badint count;std::string name;
// Goodint count = 0;std::string name;2. Use Meaningful Names
Section titled “2. Use Meaningful Names”// Badint x, y, z;double d;
// Goodint numberOfStudents;double averageScore;3. Prefer const for Constants
Section titled “3. Prefer const for Constants”// Bad#define PI 3.14159 // Macro, no type checking
// Goodconst double PI = 3.14159;constexpr double PI = 3.14159; // If known at compile time4. Use auto Sparingly
Section titled “4. Use auto Sparingly”// Good: when type is obviousauto it = container.begin();auto result = calculate();
// Bad: when it reduces readabilityauto x = someFunction(); // What type is x?Complete Example
Section titled “Complete Example”#include <iostream>#include <string>#include <vector>
int main() { // Integer types int age = 25; unsigned int population = 330000000; long long nationalDebt = 34000000000000LL;
// Floating-point types double pi = 3.14159265358979; float price = 19.99f;
// Character char grade = 'A';
// Boolean bool isStudent = true;
// String (std::string is a class, not primitive) std::string name = "John Smith";
// Container std::vector<int> scores{95, 87, 92, 88};
// Output std::cout << "Name: " << name << std::endl; std::cout << "Age: " << age << std::endl; std::cout << "Grade: " << grade << std::endl; std::cout << "Is Student: " << std::boolalpha << isStudent << std::endl; std::cout << "Pi: " << pi << std::endl;
return 0;}Key Takeaways
Section titled “Key Takeaways”- Variables store data in named memory locations
- C++ has fundamental types: integers, floating-point, characters, and booleans
- Use appropriate types for your data (e.g.,
intfor integers,doublefor decimals) - Always initialize variables before use
- Prefer brace initialization
{}to prevent narrowing conversions - Use
constandconstexprfor constants - Be aware of implicit type conversions and potential data loss
- Choose meaningful variable names
Next Steps
Section titled “Next Steps”Now let’s learn about operators in C++.
Next Chapter: 05_operators.md - Operators and Expressions