C++ Variables
Variables in C++
1. Declaration and Initialization:
You declare a variable by specifying its data type and name. Optionally, you can initialize it with a value at the time of declaration.
// Declaration
int age;
// Declaration and Initialization
double pi = 3.14;
2. Data Types:
C++ supports various data types, including:
- Primitive Data Types:
int
: Integer typefloat
: Single-precision floating-point typedouble
: Double-precision floating-point typechar
: Character typebool
: Boolean type
int count = 5;
float temperature = 98.6;
char grade = 'A';
bool isSunny = true;
- Derived Data Types:
- Arrays, pointers, references, and user-defined types (structures and classes).
3. Naming Rules:
- Variable names must begin with a letter (a-z, A-Z) or an underscore (
_
). - Subsequent characters can be letters, numbers, or underscores.
- C++ is case-sensitive, so
age
andAge
are different variables.
int myVariable;
double averageScore;
4. Initialization:
Variables can be initialized at the time of declaration, or they can be assigned a value later in the program.
int apples = 10; // Initialized at the time of declaration
double price;
price = 1.99; // Assigned a value later
5. Constants:
You can use the const
keyword to create constants, variables whose values cannot be changed.
const double PI = 3.14159;
const int MAX_VALUE = 100;
6. Scope:
Variables have a scope, which is the portion of the program where the variable can be accessed. For example, a variable declared within a function is local to that function.
void myFunction() {
int localVar = 5; // Local variable
// ...
}
int main() {
// localVar is not accessible here
// ...
return 0;
}
7. Dynamic Memory Allocation:
You can use the new
operator to allocate memory for variables dynamically. This involves creating variables at runtime and is typically associated with pointers.
int* dynamicVar = new int; // Dynamically allocated integer variable
// ...
delete dynamicVar; // Release the allocated memory
8. Type Inference (C++11 and later):
In modern C++, you can use auto
to let the compiler automatically infer the data type.
auto speed = 55.5; // Compiler infers speed as a double
Understanding how to declare, initialize, and use variables is fundamental to writing effective C++ programs. Practice with different types of variables and explore their interactions in various contexts to build a strong foundation in C++ programming.