Paramclasses Academy - Blog

Tutorials Details

←
Post 5 of 15
→

What is Variables and Constants in C

What is Variables and Constants in C

October 13, 2026

1. Introduction

Variables and constants are fundamental concepts in C programming. They allow a program to store data, use that data in calculations, and produce results.

For example, a student marks calculator may store a student's name, marks, total marks, and percentage using variables. A fixed maximum mark, such as 100, can be represented by a constant.

By the end of this module, you will understand how to declare, initialize, and use variables and constants in C.

2. What Is a Variable?

A variable is a named object used to store a value that can change while a program runs.

For example:

int age = 20;

Here:

  • int specifies the data type.

  • age is the variable name.

  • 20 is the initial value.

The value can be changed later:

age = 21;

Now, age stores 21.

3. Declaring and Initializing Variables

Variable declaration

A declaration specifies the variable's name and data type.

Syntax:

data_type variable_name;

Examples:

int age;
float price;
char grade;
double distance;

Variable initialization

Initialization means giving a variable its initial value.

int age = 20;
float price = 99.50f;
char grade = 'A';
double distance = 1234.567;

You can also declare a variable first and assign a value later:

int score;
score = 85;

Important: A local variable that has not been initialized has an indeterminate value. Do not read it before assigning a valid value.

4. Rules for Naming Variables

C has specific rules for variable names.

  • A name can contain letters, digits, and underscores (_).

  • A name must not begin with a digit.

  • Spaces are not allowed.

  • C keywords, such as int, if, and return, cannot be used as variable names.

  • Variable names are case-sensitive: age, Age, and AGE are different identifiers.

Valid names

Invalid names

age

2age

student_name

student name

totalMarks

total-marks

value1

float

_count

my variable

Best practice: Use meaningful names such as totalMarks, studentAge, and accountBalance instead of unclear names such as x1 or abc.

5. Example: Using Variables in C


#include <stdio.h>

int main(void) {
    int age = 20;
    float marks = 85.5f;
    char grade = 'A';

    printf("Age: %d\n", age);
    printf("Marks: %.1f\n", marks);
    printf("Grade: %c\n", grade);

    return 0;
}

Output:

Age: 20
Marks: 85.5
Grade: A

Explanation:

  • %d displays an int.

  • %f displays a floating-point value; %.1f displays one digit after the decimal point.

  • %c displays a single character.

6. Changing the Value of a Variable

A variable can be updated whenever the program needs a different value.

#include <stdio.h>

int main(void) {
    int number = 10;

    printf("Before: %d\n", number);

    number = 25;

    printf("After: %d\n", number);

    return 0;
}

Output:

Before: 10
After: 25

You can also update a variable using arithmetic operators:

int count = 5;

count = count + 1;  // count becomes 6
count += 2;         // count becomes 8

The += operator adds a value to the existing variable and stores the result.

7. What Is a Constant?

A constant is a value that a program is intended not to change during its execution. In C, constants can be represented using literals, const objects, and macros defined with #define.

For example, the number 100 is an integer literal, while a const variable can give a meaningful name to a fixed value.

Method 1: Using const

The const keyword makes an object non-modifiable through that identifier.

Syntax:

const data_type name = value;

Example:

const float PI = 3.14159f;

You can use PI in calculations, but you cannot assign a new value to it.

#include <stdio.h>

int main(void) {
    const float PI = 3.14159f;
    float radius = 5.0f;

    float area = PI * radius * radius;

    printf("Area: %.2f\n", area);

    return 0;
}

Output:

Area: 78.54

Attempting PI = 3.14f; in this example would violate the constraint that a const-qualified object cannot be modified through that identifier.

Method 2: Using #define

The preprocessor directive #define creates a macro.

#define MAX_MARKS 100

Example:

#include <stdio.h>

#define MAX_MARKS 100

int main(void) {
    int marks = 85;

    printf("Maximum marks: %d\n", MAX_MARKS);
    printf("Student marks: %d\n", marks);

    return 0;
}

Output:

Maximum marks: 100
Student marks: 85

Unlike a const object, a macro is handled by the preprocessor through token replacement. It does not itself declare a typed C object.

const vs. #define

Feature

const

#define

Mechanism

C language qualifier

Preprocessor macro

Data type

Has a declared type

No type of its own

Scope

Follows C scope rules

Operates through preprocessing

Can be reassigned?

No, not through the const identifier

Not a variable to reassign

Typical use

Typed, non-modifiable objects

Named substitutions and compile-time configuration

Recommendation: Prefer const when you want a typed object that cannot be modified through its identifier. Use #define when a preprocessor macro is appropriate.

8. Variables vs. Constants

Feature

Variable

Constant

Purpose

Stores a value that may change

Represents a value intended to remain fixed

Example

int score = 50;

const int LIMIT = 100;

Reassignment

Allowed when valid

Not allowed for a const object through its identifier

Common use

Scores, counters, user input

Limits, fixed settings, mathematical values

9. Practical Example: Calculating a Student's Percentage

This program uses variables for marks and a constant for the maximum marks.


#include <stdio.h>

int main(void) {
    const float MAX_MARKS = 500.0f;
    float obtainedMarks;
    float percentage;

    printf("Enter obtained marks out of 500: ");

    if (scanf("%f", &obtainedMarks) != 1) {
        printf("Invalid input.\n");
        return 1;
    }

    if (obtainedMarks < 0.0f || obtainedMarks > MAX_MARKS) {
        printf("Marks must be between 0 and 500.\n");
        return 1;
    }

    percentage = (obtainedMarks / MAX_MARKS) * 100.0f;

    printf("Percentage: %.2f%%\n", percentage);

    return 0;
}

Sample output:

Enter obtained marks out of 500: 425
Percentage: 85.00%

How it works:

  1. MAX_MARKS is a constant because the maximum marks are fixed for this calculation.

  2. obtainedMarks stores the value entered by the user.

  3. scanf() reads the input, and its return value is checked.

  4. The program validates the marks before calculating the percentage.

  5. percentage stores the calculated result.

10. Common Mistakes to Avoid

  • Using an invalid name: int 2score; is invalid because an identifier cannot start with a digit.

  • Using a keyword as a name: int return; is invalid because return is reserved.

  • Reading an uninitialized local variable: Assign a valid value before reading it.

  • Changing a const object: Do not try to assign a new value to a const-qualified object.

  • Confusing character and string literals: 'A' is a character literal; "A" is a string literal.

  • Forgetting the semicolon: int age = 20; requires a semicolon.

  • Using the wrong format specifier: Match the printf() format specifier to the type of the argument.

11. Practice Exercises

1. Declare an integer variable named age and initialize it to 18.

Show answer

2. Declare a float variable named price and initialize it to 49.5.

Show answer

3. Create a constant integer named MAX_USERS with value 50.

Show answer

4. Write a statement that increases count by 1.

Show answer

Programming challenge

Write a C program that:

  1. Declares a constant named PASS_MARKS with a value of 40.

  2. Reads a student's marks.

  3. Checks whether the input is valid and marks are between 0 and 100.

  4. Prints Pass if the marks are at least PASS_MARKS; otherwise, prints Fail.

12. Interview Questions

Q1. What is a variable in C?

A variable is a named object that stores a value that can change during program execution.

Q2. What is a constant in C?

A constant represents a value intended to remain fixed. C provides mechanisms such as const and #define for expressing fixed values.

Q3. What is the difference between declaration and initialization?

Declaration introduces a variable and specifies its type. Initialization provides its initial value.

Q4. Can a const variable be changed?

A const-qualified object cannot be modified through that identifier after initialization.

Q5. Are age and Age the same variable?

No. C is case-sensitive, so they are different identifiers.

Q6. What is the purpose of #define?

It defines a preprocessor macro, commonly used for named constants and other token substitutions.

13. Quick Revision

  • Variables store values that can change.

  • Constants represent values intended to remain fixed.

  • Declare a variable using data_type variable_name;.

  • Initialize a variable by providing its initial value.

  • Use const for typed, non-modifiable objects.

  • Use #define for preprocessor macros.

  • Follow C identifier naming rules.

  • Initialize local variables before reading their values.

  • Use correct format specifiers with printf() and scanf().

14. Homework

Create a program for a simple shopping bill. It should:

  • Declare a constant for the tax rate.

  • Accept the item's price and quantity from the user.

  • Calculate the subtotal, tax, and final bill.

  • Validate user input.

  • Print the final bill with two digits after the decimal point.

←
Post 5 of 15
→