C Variables: The Complete Beginner’s Guide
In C programming, variables are used to store data that can be used and manipulated in a program. Think of a variable like a named storage box.
Let’s break down how variables work in C, how to use them, and how to avoid common mistakes.
What Is a Variable in C?
A variable is a named memory location used to store a value of a specific data type.
Example:
int age = 25;
Here, age is a variable of type int (integer) storing the value 25.
Syntax of Declaring a Variable
data_type variable_name;
Example:
data_type variable_name = value;
Example:
int score;
float temperature;
char grade;
You can also initialize a variable at the time of declaration:
int score = 100;Types of Variables in C
| Type | Example | Description |
|---|---|---|
int | int age = 25; | Stores integers |
float | float pi = 3.14; | Stores decimal numbers |
char | char grade = 'A'; | Stores single characters |
double | double salary = 50000.75; | Stores large decimal values |
long | long count = 1234567890; | Stores large integers |
Example Program: C Variables in Action
#include <stdio.h>
int main() {
int age = 30;
float height = 5.9;
char grade = 'A';
printf("Age: %d\n", age);
printf("Height: %.1f\n", height);
printf("Grade: %c\n", grade);
return 0;
}
Output:
Age: 30
Height: 5.9
Grade: AScope of Variables
| Scope | Where It’s Accessible |
|---|---|
| Local | Inside the function/block |
| Global | Outside all functions |
| Static | Retains value between function calls |
Example: Local Variable
void display() {
int x = 5; // local to display()
}
Variable Naming Rules
Follow these rules while naming variables:
- Variable names must begin with a letter or underscore (
_). - Only alphanumeric characters and underscores are allowed.
- Keywords like
int,float, orreturncannot be used. - Variable names are case-sensitive (
ageandAgeare different).
Example of Valid Names:age, _salary, number1
Example of Invalid Names:1age (starts with a digit), float (reserved keyword)
Best Practices for Using Variables
- Use descriptive names (
totalMarks, nottm) - Initialize variables before using them
- Declare variables in the smallest possible scope
- Keep your code readable by grouping related variables
- Use the correct data type for the value you store
Common Mistakes to Avoid
| Mistake | Why It’s Wrong |
|---|---|
| Using undeclared variables | Must declare before use |
| Uninitialized variables | May produce garbage values |
| Type mismatch | E.g., storing float in int loses data |
| Reserved keywords | Don’t name variable int, float, etc. |