Variables
Variables are fundamental building blocks in programming that allow you to store and manipulate data. They act as named containers for values that can change during the execution of a program.
Declaration and Initialization
Before you can use a variable, you typically need to declare it, specifying its type and name. You can also initialize it with a value at the same time.
Syntax
<type> <variableName>;
<type> <variableName> = <initialValue>;
Examples
// Declaring an integer variable
int count;
// Declaring a string variable and initializing it
string userName = "Alice";
// Declaring a boolean variable
bool isActive = true;
// Declaring a floating-point variable
double price = 99.99;
Variable Naming Conventions
Consistent naming conventions make your code more readable and maintainable. Common conventions include:
- Using descriptive names that indicate the variable's purpose.
- Starting variable names with a lowercase letter (camelCase) or using underscores (snake_case) for multi-word names, depending on the language standard.
- Avoiding reserved keywords.
Scope
The scope of a variable defines the region of your code where that variable is accessible. Common scope types include:
- Global Scope: Variables declared outside of any function or block are accessible from anywhere in the program.
- Local Scope: Variables declared within a function or block are only accessible within that specific function or block.
- Block Scope: Variables declared within a specific code block (e.g., within an
if
statement or afor
loop) are only accessible within that block.
Data Types
Variables are associated with data types, which determine the kind of data they can hold and the operations that can be performed on them. Common data types include:
Type | Description | Example Values |
---|---|---|
int |
Whole numbers | 10 , -5 , 0 |
float / double |
Decimal numbers | 3.14 , -0.5 , 1.23e4 |
string |
Sequences of characters | "Hello World" , "MSDN" |
bool |
Boolean values (true or false) | true , false |
char |
Single characters | 'A' , '%' |
Mutability
Variables can be either mutable (their value can be changed after initialization) or immutable (their value cannot be changed once assigned).
Mutable Variables
Most variables in typical programming languages are mutable.
int score = 100;
score = 150; // Value is changed
Immutable Variables (Constants)
Some languages provide keywords like const
or final
to declare immutable variables, often referred to as constants.
const double PI = 3.14159;
// PI = 3.14; // This would cause an error
Understanding and effectively using variables is crucial for writing any program. Refer to the Data Types section for more details on the types of data you can store.