Variables and Constants in C

Variables and constants are two fundamental concepts in C programming. Every program works with data — numbers, characters, or text — and that data needs to be stored somewhere. Variables and constants are the named storage locations in a program.

Variables in C

A variable is a named memory location that can store a value. The value stored in a variable can be changed during the execution of the program. Think of a variable like a box with a label — the label is the variable name, and the content inside the box is the value.

Syntax of Variable Declaration


data_type variable_name;

Examples


int age;          // declares an integer variable named age
float salary;     // declares a float variable named salary
char grade;       // declares a char variable named grade

Variable Declaration and Initialization

A variable can be declared (created) and initialized (given a value) at the same time, or separately.


#include <stdio.h>

int main()
{
    int age = 20;           // declaration + initialization
    float height = 5.9;     // declaration + initialization
    char initial = 'R';     // declaration + initialization

    printf("Age: %d\n", age);
    printf("Height: %.1f\n", height);
    printf("Initial: %c\n", initial);

    return 0;
}

Output


Age: 20
Height: 5.9
Initial: R

Changing a Variable's Value


#include <stdio.h>

int main()
{
    int score = 50;
    printf("Before: %d\n", score);

    score = 85;  // value changed
    printf("After: %d\n", score);

    return 0;
}

Output


Before: 50
After: 85

Rules for Declaring Variables

  • A variable name must begin with a letter or underscore, not a digit.
  • Variable names are case-sensitive (age and Age are different variables).
  • No spaces or special characters (except underscore) are allowed.
  • Keywords like int, float, return cannot be used as variable names.
  • A variable must be declared before it is used.

Types of Variables Based on Scope

1. Local Variables

Declared inside a function or a block. Only accessible within that function or block. They are created when the function is called and destroyed when it returns.


#include <stdio.h>

void showAge()
{
    int age = 25;   // local variable
    printf("Age: %d\n", age);
}

int main()
{
    showAge();
    // printf("%d", age);  // ERROR! age not accessible here
    return 0;
}

2. Global Variables

Declared outside all functions, usually at the top of the program. Accessible from any function in the entire program. Their value remains throughout the program's lifetime.


#include <stdio.h>

int count = 0;  // global variable

void increment()
{
    count++;    // accessible here
}

int main()
{
    increment();
    increment();
    printf("Count: %d\n", count);  // Output: Count: 2
    return 0;
}

3. Static Variables

Declared with the static keyword. A static local variable retains its value between function calls, unlike a regular local variable which is reset each time.


#include <stdio.h>

void counter()
{
    static int num = 0;  // retains value between calls
    num++;
    printf("Count: %d\n", num);
}

int main()
{
    counter();  // Count: 1
    counter();  // Count: 2
    counter();  // Count: 3
    return 0;
}

Constants in C

A constant is a named storage location whose value cannot be changed after it is set. Constants are used for values that remain fixed throughout the program, like the value of Pi, tax rates, or physical constants.

Why Use Constants?

  • Prevents accidental modification of important values.
  • Makes code more readable and self-documenting.
  • Easier to update — change the constant definition in one place to update everywhere.

Ways to Define Constants in C

Method 1 — Using #define (Macro Constant)

The #define preprocessor directive creates a macro constant. It performs a simple text substitution before compilation — every occurrence of the constant name is replaced with its value.


#include <stdio.h>

#define PI 3.14159
#define MAX_SIZE 100
#define GREETING "Hello, World!"

int main()
{
    float radius = 5.0;
    float area = PI * radius * radius;

    printf("Area of circle: %.2f\n", area);
    printf("Max size: %d\n", MAX_SIZE);
    printf("%s\n", GREETING);

    return 0;
}

Output


Area of circle: 78.54
Max size: 100
Hello, World!

Note: #define constants have no data type, and no semicolon is needed at the end of the line.

Method 2 — Using const Keyword

The const keyword declares a variable whose value cannot be changed after initialization. Unlike #define, const variables have a specific data type.


#include <stdio.h>

int main()
{
    const float PI = 3.14159;
    const int DAYS_IN_WEEK = 7;

    printf("PI = %.5f\n", PI);
    printf("Days in a week: %d\n", DAYS_IN_WEEK);

    // PI = 3.15;  // ERROR! Cannot modify a const variable

    return 0;
}

Output


PI = 3.14159
Days in a week: 7

Types of Constants in C

1. Integer Constants


10       // decimal constant
0755     // octal constant (starts with 0)
0xFF     // hexadecimal constant (starts with 0x)

2. Float Constants


3.14     // standard float
2.5e3    // scientific notation (2.5 × 10³ = 2500)

3. Character Constants


'A'     // character A (stored as ASCII value 65)
'5'     // character 5 (not the number 5)
'\n'    // newline escape sequence

4. String Constants


"Hello"           // string of characters
"estudy247.com"   // string with numbers and symbols

#define vs const — Comparison

Feature#defineconst
Type CheckingNo type checkingHas a specific data type
MemoryNo memory allocatedMemory is allocated
ScopeThroughout the file after declarationFollows block scope rules
DebuggingHarder to debugEasier to debug
Syntax#define PI 3.14const float PI = 3.14;

Practical Example — Using Variables and Constants


#include <stdio.h>

#define TAX_RATE 0.18   // 18% tax

int main()
{
    float price = 500.0;
    float tax_amount;
    float total;

    tax_amount = price * TAX_RATE;
    total = price + tax_amount;

    printf("Product Price : Rs. %.2f\n", price);
    printf("Tax (18%%)     : Rs. %.2f\n", tax_amount);
    printf("Total Amount  : Rs. %.2f\n", total);

    return 0;
}

Output


Product Price : Rs. 500.00
Tax (18%)     : Rs. 90.00
Total Amount  : Rs. 590.00

Multiple Variable Declaration

Multiple variables of the same type can be declared in a single line:


int a, b, c;          // declaring three integers
int x = 1, y = 2;    // declaring and initializing
float p = 3.5, q = 7.1;

Summary

Variables are named memory locations that store data which can change during program execution. Constants store fixed values that do not change. C provides two ways to define constants — #define for preprocessor macros and const for typed constants. Understanding how to properly declare, initialize, and use variables and constants is essential for writing any meaningful C program.

Leave a Comment

Your email address will not be published. Required fields are marked *