Variables & Constants in C
A variable is a named storage location used by a C program to hold a value. Constants represent values that are not intended to change during a particular part of the program. Understanding both is essential because almost every useful C program stores, changes, compares, or processes data.
A variable is a named location associated with storage that can hold a value while a C program is running.
Think of a variable as a labeled container:
VARIABLE
│
▼
┌─────────────┐
│ age │ ← name
├─────────────┤
│ 20 │ ← current value
└─────────────┘
│
▼
memory
In this example, age is the variable name and
20 is its current value.
A variable is not simply the value itself. It is a name used by the program to refer to storage that contains a value.
Programs work with changing information. For example:
- a student's marks
- a person's age
- the price of a product
- the number of employees
- a calculated result
- user input
Instead of repeatedly writing raw values, we give meaningful names to the information.
int marks = 85;
Later, the program can use marks:
printf("%d", marks);
The meaning of a raw value may not be obvious.
A meaningful name explains what the value represents.
A variable declaration tells the compiler about the variable's type and name.
int age;
Here:
| Part | Meaning |
|---|---|
int |
Data type |
age |
Variable name |
int age; │ │ │ └── variable name │ └────── data type
Beginners often use the words declaration and definition as if they always mean exactly the same thing. In C, the distinction matters.
Introduces an identifier and tells the compiler about its type or other properties.
Provides the actual definition of an entity and, for an object such as a variable, normally causes storage to be allocated when appropriate.
For a simple local variable:
int age;
This is a declaration and also a definition of the local variable.
"Every declaration is only a declaration."
In C, some declarations are also definitions. The exact distinction becomes especially important with external variables and functions.
Giving a variable its initial value when it is defined is called initialization.
int age = 20;
int age = 20;
age
│
▼
┌──────┐
│ 20 │
└──────┘
The variable is created and given its initial value in the same declaration.
int age; // declaration/definition
age = 20; // assignment
int marks = 85; // declaration/definition + initialization
| Operation | Example | Meaning |
|---|---|---|
| Declaration | int age; |
Introduces the variable. |
| Initialization | int marks = 85; |
Gives the initial value. |
| Assignment | age = 20; |
Stores a value in an already existing object. |
The = symbol in C is the assignment operator.
It does not mean mathematical equality.
int score = 50;
score = 75;
score = 90;
The variable score has one current value at a time.
Assignment can replace that current value.
Start score → 50 ↓ score = 75 ↓ score → 75 ↓ score = 90 ↓ score → 90
The name of a variable is an identifier. Identifiers are also used for functions, arrays, structures, and other programmer-defined entities.
Examples:
age
studentMarks
total
average
employee_count
studentAgetotalMarksemployeeCountaverage
xa1temp2
These may be legal, but they often communicate less meaning.
C identifiers follow specific lexical rules.
- They can contain letters, digits and underscore.
- They cannot contain spaces.
- They cannot begin with a digit.
- C identifiers are case-sensitive.
- A keyword cannot be used as an ordinary variable name.
| Identifier | Valid? | Reason |
|---|---|---|
age |
✅ | Valid identifier |
student_age |
✅ | Underscore is allowed |
marks2 |
✅ | Digits are allowed after the beginning |
2marks |
❌ | Cannot begin with a digit |
student age |
❌ | Spaces are not allowed |
float |
❌ | float is a keyword |
Uppercase and lowercase letters are different in C.
int age = 20;
int Age = 30;
printf("%d\n", age);
printf("%d\n", Age);
Here, age and Age are two different
identifiers.
age → 20 Age → 30 They are different identifiers.
Creating totalMarks and later writing
totalmarks as if they were the same variable.
Multiple variables of the same type can be declared together.
int a, b, c;
They may also be initialized:
int a = 10, b = 20, c = 30;
For beginner programs, declaring related variables separately can sometimes improve readability.
A variable declaration specifies a type. The type determines what kind of object is being declared and how its value is interpreted.
int age = 20;
float price = 99.50f;
char grade = 'A';
| Declaration | Type | Example value |
|---|---|---|
int age |
integer type | 20 |
float price |
floating-point type | 99.50f |
char grade |
character type | 'A' |
Data types are covered in detail in the next lesson.
A constant is a value that does not change during the relevant use of a program.
C provides several ways to represent constant values.
10
3.14
'A'
"Hello"
These are examples of literal values used directly in source code.
Variable
name
│
▼
┌──────┐
│ 20 │
└──────┘
│
└── can be changed
Constant
100
│
└── fixed value
A literal is a value written directly in the source code.
| Literal | Example |
|---|---|
| Integer literal | 100 |
| Floating-point literal | 3.14 |
| Character constant | 'A' |
| String literal | "Hello" |
const Keyword
The const qualifier can be used when an object should
not be modified through that particular declaration.
const int MAX_MARKS = 100;
After initialization, attempting to modify the object through
this const-qualified declaration is not allowed.
const int MAX_MARKS = 100;
/* MAX_MARKS = 120; ← constraint violation */
const is a type qualifier. It is not the same
mechanism as a preprocessor macro.
#define
The preprocessor can define a macro that represents a replacement sequence.
#define PI 3.14159
Later:
double area = PI * radius * radius;
Before compilation, the preprocessor processes the macro according to the rules of preprocessing.
PI defined with #define is a macro,
not a C variable.
const vs #define
| Feature | const |
#define |
|---|---|---|
| Handled by | C compiler | Preprocessor |
| Has a C type | Yes | Macro replacement itself has no C type |
| Uses identifier | Yes | Yes |
| Scope rules | Follows C declaration/scope rules | Controlled by preprocessing directives |
| Example | const int MAX = 100; |
#define MAX 100 |
When you need a typed object that should not be modified,
const is often a clear choice. Macros have
important uses, but they should not be confused with variables.
A variable declared inside a function or block generally has block scope and is accessible only within the relevant scope.
int main(void)
{
int age = 20;
printf("%d", age);
return 0;
}
Here, age is declared inside main.
main() │ ├── age │ ├── printf() │ └── return
int main(void)
{
int x = 10;
{
int y = 20;
printf("%d %d", x, y);
}
return 0;
}
The inner block can use x because x
belongs to an enclosing scope. The variable y
belongs to the inner block.
main block
│
├── x
│
└── inner block
│
└── y
A variable defined outside all functions has file scope by default. Such a variable is commonly called a global variable.
int count = 0;
int main(void)
{
count = 10;
printf("%d", count);
return 0;
}
Global variables can be accessed according to their linkage and scope rules. These topics become more important when studying storage classes and multi-file programs.
A local automatic variable that is defined without an initializer does not automatically receive a useful value.
int main(void)
{
int x;
printf("%d", x);
return 0;
}
Reading an uninitialized automatic object can produce an indeterminate value and may lead to undefined behavior depending on how the value is used.
Prefer:
int x = 0;
int balance = 1000;
balance = 750;
balance = balance + 250;
After the first assignment, balance becomes
750. The next statement calculates
750 + 250 and stores the result.
balance = 1000
│
▼
balance = 750
│
▼
balance = 750 + 250
│
▼
balance = 1000
#include <stdio.h>
int main(void)
{
int marks1 = 80;
int marks2 = 90;
int total;
total = marks1 + marks2;
printf("Total = %d\n", total);
return 0;
}
Let's read it like a programmer.
Program │ ├── #include <stdio.h> │ └── provides declaration for printf() │ ├── main() │ ├── marks1 │ └── 80 │ ├── marks2 │ └── 90 │ ├── total │ └── marks1 + marks2 │ ├── printf() │ └── displays total │ └── return 0
The important point is that the variables allow the program to give names to the data it is processing.
Two ideas are important when studying variables:
Where an identifier can be referred to in the source code.
The period during program execution for which an object exists.
These concepts are closely related to storage duration and storage classes, which will be studied later.
- Using a variable before giving it a meaningful value.
- Using a keyword as a variable name.
- Starting an identifier with a digit.
- Forgetting that C is case-sensitive.
-
Confusing
=with mathematical equality. -
Trying to modify a
const-qualified object. -
Assuming
#definecreates a normal C variable.
= equality?
No. In an assignment such as x = 10;,
the value on the right is stored in the object on the left.
const the same as
#define?
No. const is part of the C type system.
#define defines a preprocessing macro.
No. A variable is an object identified by a name in the C program. The implementation determines how the object is represented and stored.
No. A const-qualified object is not modifiable
through that declaration.
C PROGRAM
int age = 20;
float price = 99.5f;
char grade = 'A';
│
▼
┌──────────────┐
│ age │
│ 20 │
├──────────────┤
│ price │
│ 99.5 │
├──────────────┤
│ grade │
│ A │
└──────────────┘
Names in the program
↓
Objects holding values
↓
Program operations use those values
| Concept | Remember |
|---|---|
| Variable | Named object whose stored value can change when modifiable. |
| Declaration | Introduces an identifier and its relevant type information. |
| Initialization | Provides the initial value when an object is defined. |
| Assignment | Stores a new value in an existing modifiable object. |
| Identifier | Name used for a C entity. |
const |
Qualifies an object so it is not modifiable through that declaration. |
#define |
Defines a preprocessing macro. |
| Case-sensitive | age and Age are different identifiers. |
age and Age different?
MAX = 100 a constant declaration?
MAX = 100 is an assignment
expression and requires a suitable previously declared
modifiable object named MAX.
const and
#define?
const is part of the C type system and
qualifies an object. #define creates a
preprocessing macro replacement.
C Variables & Constants — Interview Questions
These questions focus on the concepts commonly tested in technical interviews and placement examinations.
- What is a variable? A named object used by a program to store a value.
- What is initialization? Giving an object its initial value when it is defined.
- What is assignment? Storing a new value in an existing modifiable object.
- Why is C case-sensitive? Identifiers with different letter case are distinct.
- What is a constant? A value or object that is intended not to change in the relevant context.
-
What is
const? A qualifier that prevents modification through that declaration. -
What is
#define? A preprocessing directive used to define macros. - Can a variable name begin with a number? No.
Variables & Constants — Placement Tips
- Remember the difference between declaration, initialization and assignment.
-
Never confuse
=with==. - Remember that C identifiers are case-sensitive.
-
Know why
2valueis invalid butvalue2is valid. -
Know the conceptual difference between
constand#define. - Understand why using an uninitialized automatic variable is dangerous.
Store and Display a Value
Create an integer variable named age,
initialize it with 20, and print its value.
int age = 20; and print it using
printf().
Your Code
Input
Output
#include <stdio.h>
int main(void)
{
int age = 20;
printf("%d\n", age);
return 0;
}
Read and Store a Number
Create an integer variable and read one integer from the user. Then print the value.
scanf() to read
the value, and printf() to display it.
Your Code
Input
Output
#include <stdio.h>
int main(void)
{
int number;
scanf("%d", &number);
printf("%d\n", number);
return 0;
}
Change a Variable
Create an integer variable initialized to
10. Change its value to 25
using assignment and print the final value.
int value = 10;, then use
value = 25;.
Your Code
Input
Output
#include <stdio.h>
int main(void)
{
int value = 10;
value = 25;
printf("%d\n", value);
return 0;
}
Calculate Total Using Variables
Read two integers into two variables and print their sum.
scanf(), calculate their sum, and
print the result.
Your Code
Input
Output
#include <stdio.h>
int main(void)
{
int a, b;
int sum;
scanf("%d %d", &a, &b);
sum = a + b;
printf("%d\n", sum);
return 0;
}
Use a Constant Maximum
Define a constant maximum mark of 100
using const, read a student's mark,
and print the mark along with the maximum.
const int MAX_MARKS = 100;
and another integer variable for the student's mark.
Your Code
Input
Output
#include <stdio.h>
int main(void)
{
const int MAX_MARKS = 100;
int marks;
scanf("%d", &marks);
printf("Marks = %d\n", marks);
printf("Maximum = %d\n", MAX_MARKS);
return 0;
}
More Problems to Try
- Read a student's age and print it.
- Read three numbers and calculate their average.
- Store the price of a product in a variable and print it.
-
Create a
consttax rate and calculate tax. - Swap two integer variables using a temporary variable.
- Read marks in three subjects and calculate total and average.
- Create meaningful variable names for a student record.
- Identify invalid variable names from a list of identifiers.
Variables & Constants — What You Must Remember
- A variable is a named object used to store data.
- A declaration introduces an identifier and its type information.
- Initialization gives an object its initial value.
- Assignment changes the value of a modifiable object.
- C identifiers are case-sensitive.
- Variable names cannot begin with digits.
-
constqualifies an object as non-modifiable through that declaration. -
#definecreates a preprocessing macro, not a normal C variable. - Avoid using uninitialized automatic variables.
- Meaningful variable names make programs easier to understand.