2. C++ Variables and Data Types
A variable is a named container that holds a value in memory. Unlike Python, C++ is a statically typed language — you must declare the type of every variable before using it. The compiler uses this information to allocate the correct amount of memory.
This explicit typing catches errors at compile time, making C++ programs more reliable and faster than dynamically typed languages. Understanding C++ data types is the foundation of writing efficient C++ code.
Declaring Variables
In C++, you declare a variable by specifying its type followed by the variable name. You can optionally initialize it with a value at the same time.
#include <iostream> int main() { int age = 25; // Integer (whole number) double height = 5.9; // Double (decimal number) char grade = 'A'; // Character (single letter) bool isActive = true; // Boolean (true/false) std::cout << "Age: " << age << std::endl; std::cout << "Height: " << height << std::endl; std::cout << "Grade: " << grade << std::endl; std::cout << "Active: " << isActive << std::endl; return 0; }
Notice that int holds whole numbers, double holds decimal numbers, char holds a single character (always in single quotes), and bool holds true or false. In C++, bool outputs as 1 (true) or 0 (false).
Variable Naming Rules
Variable names in C++ must follow specific rules, just like in Python. Breaking these rules will cause a compilation error.
#include <iostream> int main() { // Valid variable names int my_age = 30; int _score = 100; int playerHealth = 75; int PlayerHealth = 100; // Different from playerHealth std::cout << "my_age: " << my_age << std::endl; std::cout << "_score: " << _score << std::endl; std::cout << "playerHealth: " << playerHealth << std::endl; std::cout << "PlayerHealth: " << PlayerHealth << std::endl; return 0; }
Variable names must start with a letter or underscore, can contain letters, numbers, and underscores, and are case-sensitive. C++ keywords like int, class, and return cannot be used as variable names.
Common Data Types
C++ provides several basic data types, each with a specific size and range of values. The exact size can vary depending on the system, but these are the standard ranges.
#include <iostream> int main() { int integerNum = 42; // Whole numbers (typically 4 bytes) float floatNum = 3.14f; // Single-precision decimal (4 bytes) double doubleNum = 3.14159; // Double-precision decimal (8 bytes) char letter = 'A'; // Single character (1 byte) bool flag = true; // True or false (1 byte) std::cout << "Integer: " << integerNum << std::endl; std::cout << "Float: " << floatNum << std::endl; std::cout << "Double: " << doubleNum << std::endl; std::cout << "Char: " << letter << std::endl; std::cout << "Bool: " << flag << std::endl; return 0; }
Use int for whole numbers, float for decimal numbers when memory is a concern, double for more precision in calculations, char for single characters, and bool for logical values.
Type Modifiers
C++ allows you to modify basic data types with keywords that change their size or range. These modifiers give you fine control over memory usage.
#include <iostream> int main() { short int shortVar = 32767; // 2 bytes, smaller range long int longVar = 2147483647; // 4 or 8 bytes, larger range unsigned int unsignedVar = 4294967295U; // Only positive values std::cout << "Short: " << shortVar << std::endl; std::cout << "Long: " << longVar << std::endl; std::cout << "Unsigned: " << unsignedVar << std::endl; return 0; }
short reduces memory usage for small integers, long increases range for larger numbers, and unsigned stores only positive values, doubling the maximum positive range.
Constant Variables
Use the const keyword to declare variables whose values should never change. This is essential for values like PI, tax rates, or configuration settings.
#include <iostream> #include <string> int main() { const double TAX_RATE = 0.08; const int MAX_SCORE = 100; const std::string APP_NAME = "C++ Mastery"; double price = 49.99; double total = price + (price * TAX_RATE); std::cout << "App: " << APP_NAME << std::endl; std::cout << "Price: $" << price << std::endl; std::cout << "Total: $" << total << std::endl; std::cout << "Max Score: " << MAX_SCORE << std::endl; return 0; }
Attempting to change a const variable after declaration will cause a compilation error. This catches bugs early and makes your code more maintainable.
Type Inference with auto
Modern C++ introduces the auto keyword, which lets the compiler automatically deduce the type of a variable from its initializer. This reduces verbosity without losing type safety.
#include <iostream> int main() { auto number = 42; // int auto pi = 3.14159; // double auto letter = 'Z'; // char auto name = "C++"; // const char* std::cout << "number: " << number << std::endl; std::cout << "pi: " << pi << std::endl; std::cout << "letter: " << letter << std::endl; std::cout << "name: " << name << std::endl; return 0; }
auto is especially useful when dealing with complex types like iterators or lambda expressions, where writing the full type name would be cumbersome.
Knowledge Check
Ready to test your understanding of 2. C++ Variables and Data Types?