What is a Variable?
In C++, a variable is a named storage location in memory that holds a value of a specific data type. Variables allow you to store and manipulate data in your programs.
Variable Declaration
To declare a variable in C++, you specify its type followed by its name:
int age; // Declares an integer variable named 'age'
double price; // Declares a double-precision floating-point variable
char initial; // Declares a character variable
Variable Initialization
You can initialize variables when you declare them:
int score = 100; // Initialized with value 100
double pi = 3.14159; // Initialized with pi value
char grade = 'A'; // Initialized with character 'A'
bool is_valid = true; // Initialized with boolean true
C++11 introduced uniform initialization using braces:
int count{10}; // Initialized with value 10
double temperature{36.6}; // Initialized with 36.6
char letter{'B'}; // Initialized with 'B'
Fundamental Data Types
Type | Description | Size (bytes) | Range | Example |
---|---|---|---|---|
int | Integer numbers | 4 | -2,147,483,648 to 2,147,483,647 | int count = 42; |
short | Short integer | 2 | -32,768 to 32,767 | short temp = -100; |
long | Long integer | 4 or 8 | Platform dependent | long population = 7900000000; |
float | Single-precision floating point | 4 | ±3.4e±38 (~7 digits) | float temp = 98.6f; |
double | Double-precision floating point | 8 | ±1.7e±308 (~15 digits) | double pi = 3.1415926535; |
char | Single character | 1 | -128 to 127 or 0 to 255 | char grade = 'A'; |
bool | Boolean value | 1 | true or false | bool isReady = true; |
Type Modifiers
C++ provides type modifiers to alter the meaning of the basic data types:
- signed - Default, can hold both positive and negative values
- unsigned - Can hold only positive values, doubles the positive range
- short - Half the default size
- long - Twice the default size (or more)
- long long - At least 64 bits (C++11)
unsigned int positiveOnly = 40000;
short int smallNumber = 100;
long int bigNumber = 3000000000;
long long int veryBigNumber = 9000000000000000000;
unsigned short int smallPositive = 65000;
Variable Scope
Variables in C++ have different scopes depending on where they are declared:
Local Variables
- Declared inside a function or block
- Only accessible within that function/block
- Created when the block is entered, destroyed when exited
- Also called automatic variables
void myFunction() {
int localVar = 10; // Local variable
{
int innerVar = 5; // Local to this inner block
}
// innerVar not accessible here
}
Global Variables
- Declared outside all functions
- Accessible throughout the program
- Exist for the entire program lifetime
- Should be used sparingly
int globalVar = 20; // Global variable
void function1() {
globalVar = 30; // Can modify globalVar
}
void function2() {
int globalVar = 5; // Local variable shadows global
}
Constants
Constants are variables whose values cannot be changed after initialization:
const Keyword
The traditional way to define constants:
const double PI = 3.14159;
const int MAX_USERS = 100;
// Error: Cannot modify const
// PI = 3.14;
constexpr (C++11)
For compile-time constants:
constexpr int ARRAY_SIZE = 100;
constexpr double GRAVITY = 9.8;
// Can be used where compile-time constants are required
int arr[ARRAY_SIZE];
Best Practices
- Use meaningful names:
studentCount
instead ofsc
- Initialize variables when declaring them to avoid undefined behavior
- Limit variable scope as much as possible (prefer local over global)
- Use constants for values that shouldn't change
- Choose appropriate data types based on the needed range and precision
- Follow naming conventions consistently (camelCase, snake_case, etc.)
- Avoid magic numbers - use named constants instead of literal values
- Be consistent with variable declarations - one per line is often clearer
- Consider using type aliases (typedef or using) for complex types
Common Pitfalls
- Uninitialized variables - May contain garbage values
- Integer overflow - When a value exceeds its type's capacity
- Floating-point precision errors - Due to binary representation
- Naming conflicts - Especially with global variables
- Scope shadowing - When a local variable hides a global one
- Type mismatches - Assigning values outside valid range
- Character vs. integer confusion - chars are actually small integers
// Pitfall: Uninitialized variable
int count;
cout << count; // Undefined behavior
// Pitfall: Integer overflow
short small = 32767;
small++; // Overflow - undefined behavior