๐ค 3. Variables & Constants in C
A variable gives a name to storage that holds a value, such as a studentโs marks. A constant represents a fixed value, such as a limit used in a calculation. This lesson explains how to declare names, give variables their first values, and update them.
A variable names storage that holds a value while the program runs.
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.
The name identifies the variable; the value is the data it currently holds. Assigning a new value can change that data while keeping the same name.
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
A meaningful name shows what a value represents. For example, marks is easier to understand in a calculation than an unexplained number.
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
A declaration tells the compiler about a name. A definition also supplies the variable or function itself. One line can do both, as the local-variable example below shows.
Tells the compiler about a name and its type or other properties.
Defines the variable or function. Defining an ordinary variable makes storage available according to its storage duration; defining a function supplies its body.
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."
Some declarations are also definitions. Keep this distinction in mind when you later use external variables and separate source files.
Giving a variable its initial value when it is defined is called initialization.
int age = 20;
int age = 20;
age
โ
โผ
โโโโโโโโ
โ 20 โ
โโโโโโโโ
The same declaration introduces the variable and gives it its first value.
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 short names can be valid, but they may not explain what the values mean.
C has rules for spelling identifiers, the names used for variables and functions.
- 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 declaration gives a variable a type. That type describes the values it can hold and affects the operations you can perform with it.
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
A macro gives a name to replacement text that the preprocessor uses before compilation.
#define PI 3.14159
Later:
double area = PI * radius * radius;
Before compilation, the preprocessor replaces uses of this object-like macro with its replacement text.
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 value with a type that should not be changed,
const is often a clear choice. Macros have
important uses, but they should not be confused with variables.
A local variable is declared inside a function or block. Its name can be used only within the part of the source where that declaration is in 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;
}
A global variableโs declaration and linkage determine where its name can be used, including whether it can be shared across source files. The Storage Classes lesson explains these rules.
An ordinary local variable without an initializer does not start with a reliable value. Give it a value before reading it.
int main(void)
{
int x;
printf("%d", x);
return 0;
}
Its value is indeterminate, meaning it is not a value you can rely on. Reading an uninitialized local int can cause undefined behaviour, so do not describe it as a predictable โgarbageโ number.
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;
}
Trace each assignment in order and keep track of the current values.
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:
The part of the source where a name can be used.
The part of program execution during which the variableโs storage 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
3.28 Integer Literal Bases and Type Suffixes
An integer literal can use decimal, octal (leading 0), hexadecimal (0x) or, in C23, binary (0b). Suffixes such as U and L affect the literal type. Leading zeros matter: 010 means octal eight, not decimal ten.
Complete C program:
#include <stdio.h>
int main(void)
{
unsigned int flags = 0x0FU;
printf("Decimal: %u\n", flags);
printf("Octal 010: %d\n", 010);
printf("Hexadecimal: %X\n", flags);
return 0;
}
Expected output:
Decimal: 15
Octal 010: 8
Hexadecimal: F
Step-by-step explanation:
- 0x0FU uses a hexadecimal value and an unsigned suffix.
- The value 010 is an octal integer constant.
- The conversion specifiers control how the values appear on screen.
3.29 Quick Revision
๐ Declaration introduces a variable with its type and name.
๐ Initialization gives an initial value when an object is defined.
๐ Assignment changes the stored value when the object is modifiable.
๐ C identifiers are case-sensitive.
๐ Keywords cannot be used as identifiers.
๐ const can make an object read-only through that identifier.
๐ #define creates a preprocessor macro.
3.30 Quick MCQs
Select an answer first, then click Check Answer. Your choice will be marked immediately, and the correct answer with explanation will appear below.
The single equals sign (=) is the assignment operator in C. It stores the value of the right-hand expression in the object on the left.
student_name is valid because it begins with a letter and contains only letters and an underscore. An identifier cannot start with a digit, contain spaces, or use a C keyword such as float.
const is the C type qualifier used to indicate that an object should not be modified through that identifier.
C identifiers are case-sensitive. For example, age, Age, and AGE are treated as different identifiers.
int age; is valid because int is a C type keyword and age is a valid identifier. Identifiers cannot begin with a digit, and integer/number are not C built-in type keywords.
3.31 ๐ฏ 5 Programming Problems
Try each problem yourself first. Use ๐ป Solve It Yourself to write and test your C program. Use Hint only when needed, and Show Program if you want to study the complete solution.
Declare variables to store a student's age, marks and grade and print them.
Input: Age, marks and grade.
Output: Print the three values with clear labels.
C Code Editor
Sample Input
Program Output
Run your program to see the output.
Test Cases
#include <stdio.h>
int main()
{
int age;
float marks;
char grade;
scanf("%d %f %c", &age, &marks, &grade);
printf("Age = %d\n", age);
printf("Marks = %.2f\n", marks);
printf("Grade = %c", grade);
return 0;
}Write a C program to exchange the values of two variables using a third variable.
Input: Two integers a and b.
Output: Print the values after swapping.
C Code Editor
Sample Input
Program Output
Run your program to see the output.
Test Cases
#include <stdio.h>
int main()
{
int a, b, temp;
scanf("%d %d", &a, &b);
temp = a;
a = b;
b = temp;
printf("a = %d, b = %d", a, b);
return 0;
}Write a C program to calculate the total and average of three marks.
Input: Three marks.
Output: Print total and average rounded to two decimal places.
C Code Editor
Sample Input
Program Output
Run your program to see the output.
Test Cases
#include <stdio.h>
int main()
{
float m1, m2, m3;
float total, average;
scanf("%f %f %f", &m1, &m2, &m3);
total = m1 + m2 + m3;
average = total / 3.0f;
printf("Total = %.2f\n", total);
printf("Average = %.2f", average);
return 0;
}Create a constant for PI and calculate the area of a circle.
Input: Radius of the circle.
Output: Print the area rounded to two decimal places.
C Code Editor
Sample Input
Program Output
Run your program to see the output.
Test Cases
#include <stdio.h>
int main()
{
const double PI = 3.14159;
double radius;
double area;
scanf("%lf", &radius);
area = PI * radius * radius;
printf("Area = %.2f", area);
return 0;
}Write a program to calculate the total price of three products.
Input: Three product prices.
Output: Print the total price rounded to two decimal places.
C Code Editor
Sample Input
Program Output
Run your program to see the output.
Test Cases
#include <stdio.h>
int main()
{
double p1, p2, p3;
double total;
scanf("%lf %lf %lf", &p1, &p2, &p3);
total = p1 + p2 + p3;
printf("Total Price = %.2f", total);
return 0;
}3.32 Key Takeaway
What data do I need?
What type should each data item have?
Which values can change?
Which values should remain unchanged?
Choosing appropriate variables and constants is one of the first steps toward writing clear and reliable programs.
๐ฌ Variables & Constants โ Visual Flow
Follow how a variable is declared, receives a value, changes during execution, and differs from a constant.
๐ฌ Variables & Constants Visualizer
See the life cycle of a variable and how a constant differs from a modifiable variable.
int age;age = 20age = 2525MAX = 100๐ Program Tracing โ Variables & Constants
โ
๐ค Variables & Constants โ Interview Questions
๐ก Variables & Constants โ Extra Tips
- Be ready to explain the difference between declaration, initialization, and assignment with one short example.
- Remember that an uninitialized automatic local variable has an indeterminate value; do not use it before assigning a valid value.
- Do not confuse = with ==. Assignment stores a value; equality comparison checks whether values are equal.
- Use meaningful variable names in coding rounds because readable code is easier to verify and debug.
- Know the practical difference between a const-qualified object and a #define macro.
โ๏ธ Variables & Constants โ Extra Practice Questions
- Identify the type, variable name and initial value in
double salary = 45000.50;. - Predict the final value of
xafterint x = 5; x = x + 3; x = x * 2;. - Find the invalid identifiers among
total_marks,2value,float,student2, andtotal-price. - Write one example each for declaration, initialization and assignment using the same variable.
- Explain when you would choose a normal variable, a
constobject, and a#definemacro.