If you’ve just started your C programming journey, you’ve probably seen a lot of terms being thrown around—variables, constants, keywords, and so on. Among these, variables and constants are the true heroes of your C code. Without them, your program would be like a story without characters.
In this blog, we’ll break down what variables and constants are in C, why they matter, and how you can use them with real-life examples.
What is a Variable?
Think of a variable as a box in your computer’s memory that stores some information (like a number, character, or decimal value). The special thing about this box is that the value inside it can change during program execution.
In simple words: A variable is a named location in memory that stores data, and its value can vary (change).
Rules for Naming Variables
Before we see them in action, here are some rules:
1. Variable names must start with a letter or underscore (_).
2. They cannot contain spaces or special characters like @, $, %.
3. They are case-sensitive (age and Age are different).
4. Keywords like int, float, if, else cannot be used as variable names.
Examples of valid variable names:
Declaring Variables
Syntax:
#include <stdio.h> int main() { int age = 20; // integer variable float pi = 3.14; // float variable char grade = 'A'; // character variable printf("Age: %d\n", age); printf("Value of Pi: %.2f\n", pi); printf("Grade: %c\n", grade); return 0; }
Output:
What is a Constant?
Declaring Constants in C
Example 2: Using Constants
#include <stdio.h> #define MAX_STUDENTS 50 // constant using #define int main() { const float PI = 3.14159; // constant using const keyword printf("Value of PI: %.2f\n", PI); printf("Maximum Students allowed: %d\n", MAX_STUDENTS); return 0; }
Output:
Difference Between Variables and Constants
Feature | Variable | Constant |
---|---|---|
Value | Can change during program | Fixed |
Declaration | int age = 20; | const int age = 20; or #define AGE 20 |
Storage | Stored in memory | Stored in memory (const) or replaced during compilation (#define) |
Example 3: Variables vs Constants in Action
#include <stdio.h> #define TAX_RATE 0.05 // constant int main() { int price = 1000; // variable float tax = price * TAX_RATE; int total = price + tax; printf("Price: %d\n", price); printf("Tax: %.2f\n", tax); printf("Total Price: %d\n", total); // price = 1200; // ✅ Allowed (variable can change) // TAX_RATE = 0.1; // ❌ Error (constant cannot be changed) return 0; }