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.

4.1 What Is a Variable?

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.

Important:

A variable is not simply the value itself. It is a name used by the program to refer to storage that contains a value.

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

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

The meaning of a raw value may not be obvious.

With a variable

A meaningful name explains what the value represents.

4.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
4.4 Declaration vs Definition

Beginners often use the words declaration and definition as if they always mean exactly the same thing. In C, the distinction matters.

Declaration

Introduces an identifier and tells the compiler about its type or other properties.

Definition

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.

Do not memorize:

"Every declaration is only a declaration."

In C, some declarations are also definitions. The exact distinction becomes especially important with external variables and functions.

4.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 variable is created and given its initial value in the same declaration.

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

4.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
4.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 may be legal, but they often communicate less meaning.

4.9 Rules for Naming Variables

C identifiers follow specific lexical rules.

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

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

4.12 Data Type and Variable Relationship

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.

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

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

Important distinction:

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

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

4.18 Local 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
4.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
4.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;
}

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.

4.21 Uninitialized Variables

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

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;
4.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
4.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;
}

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.

4.24 Scope and Lifetime — First Introduction

Two ideas are important when studying variables:

Scope

Where an identifier can be referred to in the source code.

Lifetime

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.

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

4.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
4.28 Quick Revision
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.
Practice Your Understanding
1 What is the difference between initialization and assignment?
2 Why are age and Age different?
3 Is MAX = 100 a constant declaration?
4 What is the difference between const and #define?
5 Why should local variables generally be initialized before use?
INTERVIEW PREPARATION

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.
PLACEMENT TIPS

Variables & Constants — Placement Tips

  1. Remember the difference between declaration, initialization and assignment.
  2. Never confuse = with ==.
  3. Remember that C identifiers are case-sensitive.
  4. Know why 2value is invalid but value2 is valid.
  5. Know the conceptual difference between const and #define.
  6. Understand why using an uninitialized automatic variable is dangerous.
PRACTICE
Variables & Constants Practice
0 Solved
0 / 5 Completed
0% Score
Problem 1

Store and Display a Value

Create an integer variable named age, initialize it with 20, and print its value.

Problem 2

Read and Store a Number

Create an integer variable and read one integer from the user. Then print the value.

Problem 3

Change a Variable

Create an integer variable initialized to 10. Change its value to 25 using assignment and print the final value.

Problem 4

Calculate Total Using Variables

Read two integers into two variables and print their sum.

Problem 5

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.

EXTRA PRACTICE

More Problems to Try

  1. Read a student's age and print it.
  2. Read three numbers and calculate their average.
  3. Store the price of a product in a variable and print it.
  4. Create a const tax rate and calculate tax.
  5. Swap two integer variables using a temporary variable.
  6. Read marks in three subjects and calculate total and average.
  7. Create meaningful variable names for a student record.
  8. Identify invalid variable names from a list of identifiers.
KEY TAKEAWAY

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.
  • const qualifies an object as non-modifiable through that declaration.
  • #define creates a preprocessing macro, not a normal C variable.
  • Avoid using uninitialized automatic variables.
  • Meaningful variable names make programs easier to understand.
← Previous Topic: Structure of C Program Next Topic: Data Types →