🎓 Lecture Article: Variables in C Programming
What is a Variable?
In C programming, a variable is a named memory location used to store data that can be changed during the execution of the program.
💡 Think of a variable as a labeled container where you can store, modify, and retrieve data.
🧠 Why Use Variables?
- To store user input or calculated values.
- To reuse and manipulate data during execution.
- To make programs flexible, dynamic, and interactive.
🧾 Syntax for Declaring a Variable
data_type variable_name;
Or with initialization:
data_type variable_name = value;
✅ Examples:
int age; float salary = 25000.75; char grade = 'A';
📚 Common Data Types
Data Type | Description | Example Value |
---|---|---|
int | Integer numbers | 10, -50 |
float | Decimal (floating point) numbers | 3.14, -0.005 |
char | Single characters | 'A', 'z' |
double | Double-precision float | 1.23456789 |
📌 Variable Naming Rules
- Must begin with a letter (A–Z, a–z) or an underscore
_
- Can include letters, digits, and underscores
- Cannot use C keywords (
int
,float
, etc.) - C is case-sensitive:
Total
andtotal
are different - Avoid using special characters (e.g.,
@
,#
,%
)
✅ Valid Names:
int age; float salary_2024; char _grade;
❌ Invalid Names:
int 2ndItem; // Starts with a digit float salary$; // Contains special character char int; // 'int' is a keyword
📦 Types of Variables (By Scope & Storage Class)
Type | Scope | Storage Location | Lifetime |
---|---|---|---|
Local | Inside function/block | Stack | Until block ends |
Global | Outside all functions | Data segment | Entire program |
Static | Local/global | Data segment | Entire program |
Extern | Declared elsewhere | Data segment | Entire program |
Register | CPU register | CPU (if possible) | Block |
🧪 Example Program
#include <stdio.h> int main() { int age = 25; float height = 5.9; char grade = 'B'; printf("Age: %d\n", age); printf("Height: %.1f feet\n", height); printf("Grade: %c\n", grade); return 0; }
🔍 Output:
Age: 25 Height: 5.9 feet Grade: B
❗ Common Mistakes with Variables
- Uninitialized use:
int a;
printf("%d", a);
❌ Unpredictable output - Redeclaring inside same scope:
int a = 5;
int a = 10;
❌ Error: redefinition - Using incorrect types:
char name = "Alex";
❌ Wrong: should be a string (char array)
💡 Best Practices
- Use descriptive names:
totalMarks
,userAge
,itemPrice
- Avoid single-letter names (except in loops)
- Always initialize your variables
- Match data type to the kind of data you’re storing
📝 Summary
- A variable is a named memory location used to store data.
- C is a statically typed language — variable types must be declared.
- Variable types, naming conventions, and scope are crucial to program behavior.
- Use good naming conventions and always initialize your variables.
🎯 Practice Exercise
- Declare and initialize variables of each data type.
- Write a program to calculate the area of a rectangle using
length
andwidth
variables. - Try using a variable without initialization — what happens?