๐Ÿ”ค 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.

3.1 What Is a Variable?

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.

Important:

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.

3.2 Why Do We Need Variables?

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);
Without a variable

The meaning of a raw value may not be obvious.

With a variable

A meaningful name explains what the value represents.

3.3 Variable Declaration

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
3.4 Declaration vs Definition

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.

Declaration

Tells the compiler about a name and its type or other properties.

Definition

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.

Do not memorize:

"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.

3.5 Variable Initialization

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.

3.6 Declaration, Initialization and Assignment
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.
Remember:

The = symbol in C is the assignment operator. It does not mean mathematical equality.

3.7 Variables Can Change
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
3.8 Variable Names and Identifiers

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
Good names
  • studentAge
  • totalMarks
  • employeeCount
  • average
Poor names
  • x
  • a1
  • temp2

These short names can be valid, but they may not explain what the values mean.

3.9 Rules for Naming Variables

C has rules for spelling identifiers, the names used for variables and functions.

  1. They can contain letters, digits and underscore.
  2. They cannot contain spaces.
  3. They cannot begin with a digit.
  4. C identifiers are case-sensitive.
  5. 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
3.10 C Is Case-Sensitive

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.
Common mistake:

Creating totalMarks and later writing totalmarks as if they were the same variable.

3.11 Declaring Multiple Variables

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;
Good programming practice:

For beginner programs, declaring related variables separately can sometimes improve readability.

3.12 Data Type and Variable Relationship

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.

3.13 What Is a Constant?

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
3.14 Literal Constants

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"
3.15 The 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 */
Important:

const is a type qualifier. It is not the same mechanism as a preprocessor macro.

3.16 Symbolic Constants with #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.

Important distinction:

PI defined with #define is a macro, not a C variable.

3.17 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
Modern beginner guideline:

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.

3.18 Local 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
3.19 Variables Inside Blocks
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
3.20 Global Variables

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.

3.21 Uninitialized Variables

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;
}
Do not do this:

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;
3.22 Assignment Changes the Stored Value
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
3.23 Complete Program โ€” Variables in Action
#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.

3.24 Scope and Lifetime โ€” First Introduction

Two ideas are important when studying variables:

Scope

The part of the source where a name can be used.

Lifetime

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.

3.25 Common Variable Mistakes
  1. Using a variable before giving it a meaningful value.
  2. Using a keyword as a variable name.
  3. Starting an identifier with a digit.
  4. Forgetting that C is case-sensitive.
  5. Confusing = with mathematical equality.
  6. Trying to modify a const-qualified object.
  7. Assuming #define creates a normal C variable.
3.26 Common Beginner Confusions
Confusion 1: Is = equality?

No. In an assignment such as x = 10;, the value on the right is stored in the object on the left.

Confusion 2: Is const the same as #define?

No. const is part of the C type system. #define defines a preprocessing macro.

Confusion 3: Is a variable just a memory address?

No. A variable is an object identified by a name in the C program. The implementation determines how the object is represented and stored.

Confusion 4: Can every variable be changed?

No. A const-qualified object is not modifiable through that declaration.

3.27 Variable Memory Map
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:

  1. 0x0FU uses a hexadecimal value and an unsigned suffix.
  2. The value 010 is an octal integer constant.
  3. The conversion specifiers control how the values appear on screen.
Remember: The digits 8 and 9 are not valid in octal literals. Use 0b literals only when targeting C23 or an explicitly documented extension.

3.29 Quick Revision

๐Ÿ“Œ A variable represents a storage location used by a program.

๐Ÿ“Œ 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.

1. Which symbol is used for assignment?
2. Which is a valid identifier?
3. Which keyword can be used to qualify an object as read-only?
4. Which of the following is case-sensitive in C?
5. Which is a valid declaration?
PRACTICE

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.

๐Ÿ“ˆ Variables & Constants Practice Progress
Solved0 / 5
Completed with Solution0
Total Score0 / 100
Completion0%
A problem counts as Solved when all tests pass without opening the full solution. Problems completed after viewing the solution are tracked separately.
1. Student Details Using Variables

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.

2. Swap Two Variables

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.

3. Total and Average of Three Marks

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.

4. Area of a Circle Using a Constant

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.

5. Total Price of Three Products

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.

3.32 Key Takeaway

๐ŸŽฏ Before writing a C program, ask:

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.
INTERACTIVE LEARNING

๐ŸŽฌ Variables & Constants โ€” Visual Flow

Follow how a variable is declared, receives a value, changes during execution, and differs from a constant.

PROGRAM TRACING

๐Ÿ”Ž Program Tracing โ€” Variables & Constants

INTERVIEW PREPARATION

๐ŸŽค Variables & Constants โ€” Interview Questions

1.What is a variable in C?
2.What is the difference between declaration, initialization and assignment?
3.What rules should a C identifier follow?
4.What is the difference between const and #define?
5.Why are meaningful variable names important?
PLACEMENT TIPS

๐Ÿ’ก 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.
EXTRA PRACTICE

โœ๏ธ Variables & Constants โ€” Extra Practice Questions

  1. Identify the type, variable name and initial value in double salary = 45000.50;.
  2. Predict the final value of x after int x = 5; x = x + 3; x = x * 2;.
  3. Find the invalid identifiers among total_marks, 2value, float, student2, and total-price.
  4. Write one example each for declaration, initialization and assignment using the same variable.
  5. Explain when you would choose a normal variable, a const object, and a #define macro.
โ† Previous Topic: Structure of C ProgramNext Topic: Data Types โ†’