Imagine you're solving a problem and need to store a student's age, marks, or name. The computer also needs a place to store these values.
That's where variables come in.
What is a Variable?
A variable is a named memory location used to store a value that can change during program execution.
For example:
int age = 20;
Here:
int→ data typeage→ variable name20→ value
You can think of a variable like a labeled box.
age
┌────────┐
│ 20 │
└────────┘
The label is age, and the value stored inside it is 20.
Declaring a Variable
Before using a variable, we generally declare it by specifying its data type and name.
int age;
Here, we have created an integer variable named age.
We can assign a value later:
age = 20;
Or we can do both at once:
int age = 20;
This is called initialization.
Changing a Variable's Value
One important feature of a variable is that its value can change.
int age = 20;
age = 21;
Initially, age contains 20. Later, it contains 21.
That's why it is called a variable—its value can vary.
Multiple Variables
We can create multiple variables in the same program:
int age = 20;
float height = 5.8;
char grade = 'A';
Each variable stores a different type of value.
Variable | Value | Type |
|---|---|---|
|
|
|
|
|
|
|
|
|
We'll learn these data types in detail in the Data Types topic.
Rules for Naming Variables
There are a few basic rules you need to follow:
A variable name can contain letters, digits, and
_.It cannot start with a digit.
Spaces are not allowed.
C keywords cannot be used as variable names.
C is case-sensitive.
For example:
int studentAge; // valid
int student_age; // valid
int age2; // valid
But:
int 2age; // invalid
int student age; // invalid
Also, age and Age are considered different variable names.
Simple Example
#include <stdio.h>
int main()
{
int age = 20;
printf("Age = %d", age);
return 0;
}
Output:
Age = 20
Here, the variable age stores 20, and printf() displays that value.
In Simple Words
You can remember a variable as:
A variable is a named storage location in memory whose value can change during program execution.
For example, a student's marks might change from 70 to 85, so we can store them in a variable.
Once variables are clear, the next important question is: what kind of values can a variable store? That's where Data Types in C come in.