Variables in C ๐ฆ
Mentor's Note: Think of a variable as a labeled storage box in a warehouse. You can put things in, take things out, or replace them, but the box label tells you what type of item belongs inside! ๐ก
๐ Educational Content: This tutorial is designed to align with GSEB Std 10/12, CBSE Computer Science, and BCA Sem 1 syllabus standards.
By the end of this tutorial, you'll know:
- What variables are and how the "labeled box" analogy works.
- The difference between declaring and initializing variables in C.
- The strict naming rules for variables in C (board exam favorite).
- How to print variable values using
printfformat specifiers. - The difference between local and global variables.
๐ The Scenario: The Post Office Mailboxesโ
Imagine you walk into a Post Office containing thousands of small mailboxes. To store letters or packages, each mailbox has two things:
- A Label: A unique name written on the outside (like "Box 14", "Raj_Mail", or "Rent_Due") so you know which box is which.
- A Size Limit: Some boxes are tiny slot-like mailboxes for letters, while others are large lockers for packages. You cannot put a large package into a letter slot.
To store information in a computer, the computer does the exact same thing. It reserves a small portion of its memory (a mailbox), gives it a name (a label), and restricts what kind of data can fit inside it based on its type.
In programming:
- The Mailbox is a Variable.
- The Label is the Variable Name (Identifier).
- The Contents of the box is the Value stored in the variable.
- The Box Type is the Data Type (like integer or character).
๐ Concept Explanationโ
What is a Variable?โ
A variable is a named location in a computer's memory used to store data that can be changed during program execution.
Declaration vs Initializationโ
Before you can use a variable in C, you must tell the computer about it. This is a two-step process (though it can be done in a single line):
- Declaration: Telling the compiler the name of the variable and what kind of data it will hold. This reserves memory space.
int age; // Declares an integer variable named 'age'
- Initialization: Giving an initial value to the declared variable.
age = 16; // Initializes the variable 'age' with the value 16
You can combine both steps in a single line:
int age = 16; // Declaration and initialization
Strict Variable Naming Rulesโ
In C, you cannot name variables whatever you want. The rules are strict and frequently tested in board exams:
- First character: Must be a letter (A-Z, a-z) or an underscore (
_). It cannot start with a number.- โ
int age;| โint _temp; - โ
int 32age;
- โ
- Allowed characters: Can only contain letters, numbers, and underscores. No spaces or special characters (like
$,@,#,-) are allowed.- โ
int roll_number; - โ
int roll number;| โint roll-number;
- โ
- No Keywords: You cannot use C keywords (like
int,float,return,void,if) as variable names.- โ
int return;
- โ
- Case Sensitivity: C is case-sensitive.
age,Age, andAGEare treated as three completely different variables.
๐ง Variable Scope: Local vs Globalโ
The scope of a variable determines where in your code that variable can be accessed and modified.
1. Local Variablesโ
- Where: Declared inside a function block
{ ... }. - Access: Only accessible within the function they are declared in. Other functions don't even know they exist.
- Lifetime: Created when the function starts and destroyed when the function ends.
2. Global Variablesโ
- Where: Declared outside all functions (usually at the very top of the file, below
#include). - Access: Accessible by any function anywhere in the program.
- Lifetime: Exists as long as the program is running.
๐ป Working Example: Variable Scope and Typesโ
Here is a complete C program demonstrating variable declaration, initialization, format specifiers, and scopes.
#include <stdio.h>
// Global variable (Accessible by all functions)
int globalCount = 50;
void displayAnother() {
// Local variable to displayAnother
int localVal = 5;
printf("displayAnother -> localVal: %d, globalCount: %d\n", localVal, globalCount);
}
int main() {
// Local variables to main
int age = 16;
float marks = 94.5f;
char grade = 'A';
printf("main -> age: %d\n", age);
printf("main -> marks: %.1f\n", marks);
printf("main -> grade: %c\n", grade);
printf("main -> globalCount: %d\n", globalCount);
displayAnother();
return 0;
}
// Output:
// main -> age: 16
// main -> marks: 94.5
// main -> grade: A
// main -> globalCount: 50
// displayAnother -> localVal: 5, globalCount: 50
๐ Sample Dry Runโ
Let's trace the variable values step-by-step through execution:
| Step | Line of Code Executed | Variable Name | Type | Value in Memory | Description |
|---|---|---|---|---|---|
| 1 | int globalCount = 50; | globalCount | int (Global) | 50 | Allocated in global data segment. |
| 2 | int age = 16; | age | int (Local) | 16 | Allocated on main stack frame. |
| 3 | float marks = 94.5f; | marks | float (Local) | 94.5 | Allocated on main stack frame. |
| 4 | char grade = 'A'; | grade | char (Local) | 'A' (ASCII 65) | Allocated on main stack frame. |
| 5 | displayAnother(); | localVal | int (Local) | 5 | Created on displayAnother stack frame. |
| 6 | Function exits | localVal | int | (Destroyed) | Local variable space is freed. |
๐งช Interactive Elementsโ
Try It Yourselfโ
Task: Try adding printf("%d", localVal); inside the main() function of the code above and compile it. See what error the compiler outputs.
Hint: Since localVal is local to displayAnother(), compiling this will result in an error: 'localVal' undeclared in main.
Quick Quizโ
Which of the following is a valid variable name in C?
- A)
2nd_number - B)
float - C)
total_sum - D)
price$
Explanation:
2nd_numberis invalid because it starts with a number.floatis invalid because it is a reserved keyword.price$is invalid because it contains the special character$.total_sumis valid because it starts with a letter and contains only letters and underscores.
๐ Complexity Analysisโ
- Time Complexity:
- Variable Initialization: $O(1)$ constant time.
- Variable Access: $O(1)$ constant time lookup via memory address.
- Space Complexity:
- Memory allocation: $O(1)$ auxiliary space. The program allocates a fixed number of bytes in memory (e.g. 4 bytes for
int, 4 bytes forfloat, 1 byte forchar).
- Memory allocation: $O(1)$ auxiliary space. The program allocates a fixed number of bytes in memory (e.g. 4 bytes for
๐ฏ Practice Problemsโ
Easy Level ๐ขโ
- Write a program to declare three variables: an integer for roll number, a float for temperature, and a character for section. Assign values and print them.
- Identify which of these variable names are invalid and explain why:
student age_average_markdoublenum_1
Medium Level ๐กโ
- Write a program with a global variable named
score. Modify the value ofscoreinsidemain()and print it. Then call a functionprintScore()to verify that the modified value is accessible there too.
Hard Level ๐ดโ
- Write a program where a local variable in
mainhas the exact same name as a global variable. Assign different values to both. Print the variable insidemainand explain which value gets printed and why (shadowing/masking concept).
โ Frequently Asked Questionsโ
Details
Q: What happens if I declare a variable but do not initialize it?
In C, if you declare a local variable but do not give it a value, it will contain a garbage value (whatever random bits of data were already left behind in that memory location). Always initialize your variables before reading them to avoid unpredictable bugs!Details
Q: Why is C called a "statically typed" language?
"Statically typed" means that the compiler must know the data type of every variable at compilation time. Once you declare a variable as anint, you cannot store a string in it later, and you cannot change its type during runtime (unlike Python or JavaScript).Details
Q: Why should we limit the use of global variables?
Global variables can be read and modified by any part of the program. If you have a bug where a global variable has the wrong value, you have to check every single function to find who changed it. Keeping variables local makes code modular and much easier to debug.๐ Best Practices & Common Mistakesโ
โ Best Practicesโ
- Always initialize local variables: Initialize them during declaration (e.g.
int count = 0;) to prevent reading garbage values. - Use camelCase or snake_case: Choose one naming convention and stick to it (e.g.,
studentAgeorstudent_age). - Use meaningful names: Name variables for what they represent (use
averageMarksinstead of justx).
โ Common Mistakes โ ๏ธโ
- Declaring variables inside loops repeatedly: Declaring variables inside a loop block can confuse beginners about the variable's lifetime.
- Trying to use a variable before declaring it: Writing
count = 10; int count;instead of declaring it first. - Using a keyword: Declaring
int char;orint default;.
โ Summaryโ
In this tutorial, you've learned:
- โ Variables are named boxes in memory that store values.
- โ Declaring reserves memory; initializing assigns the first value.
- โ
Variable names can contain letters, numbers, and underscores, but must start with a letter or
_. - โ Local variables exist inside functions; global variables exist across the whole program.
- โ
C is case-sensitive, meaning
ageandAgeare separate variables.
๐ก Pro Tip: Use the
constkeyword before your variable type if you want to create a variable whose value cannot be changed after initialization (e.g.,const float PI = 3.14;).
๐ Further Readingโ
Continue your learning path:
Go deeper:
---