C Notes
Learn about variables in C programming — declaration, initialization, scope, naming rules, and types of variables with practical examples and explanations.
If you've ever used a calculator to store a number in memory for later use, you already understand the basic idea behind variables. In C programming, a variable is essentially a named storage location in your computer's memory that holds a value which can change during program execution.
Think of a variable like a labeled box — you give it a name, decide what type of content it can hold, and then put values in or take values out as needed. This concept is fundamental to every C program you'll ever write.
Variable Declaration in C
Before you can use a variable in C, you must declare it. Declaration tells the compiler two things: the variable's name and the type of data it will hold.
Syntax of Variable Declaration
data_type variable_name;Examples of Variable Declaration
int age; // declares an integer variable
float salary; // declares a floating-point variable
char grade; // declares a character variable
double pi; // declares a double-precision floatYou can also declare multiple variables of the same type in a single line:
int x, y, z; // three integer variables
float length, width; // two float variablesWhat Happens During Declaration?
When you declare a variable, the compiler:
- Reserves a block of memory of the appropriate size
- Associates your chosen name with that memory address
- Notes the data type (so it knows how to interpret the stored bits)
Important: A declared but uninitialized variable in C contains a garbage value — whatever was previously in that memory location. Never assume it's zero!
Variable Initialization in C
Initialization means assigning a value to a variable at the time of declaration.
int age = 25; // declaration + initialization
float pi = 3.14159; // initialized with a float value
char letter = 'A'; // initialized with a characterYou can also separate declaration and initialization:
int count; // declaration
count = 10; // assignment (initialization later)Complete Example: Declaration and Initialization
#include <stdio.h>
int main() {
// Declaration with initialization
int age = 21;
float height = 5.9;
char initial = 'J';
// Declaration without initialization
int marks;
marks = 95; // assigned later
printf("Age: %d\n", age);
printf("Height: %.1f\n", height);
printf("Initial: %c\n", initial);
printf("Marks: %d\n", marks);
return 0;
}Age: 21 Height: 5.9 Initial: J Marks: 95
Naming Rules for Variables in C
C has strict rules about what names are valid for variables. Break any of these rules and your code won't compile.
| Rule | Valid Example | Invalid Example |
|---|---|---|
| Must begin with a letter or underscore | name, _count | 2name, @val |
| Can contain letters, digits, underscores | student1, max_val | my-var, total$ |
| Cannot be a C keyword | value, number | int, return |
| Case-sensitive | Age ≠ age ≠ AGE | — |
| No spaces allowed | first_name | first name |
| No length limit (but first 31 chars significant) | counter | — |
Best Practices for Naming Variables
- Use meaningful names:
studentAgeinstead ofx - Use camelCase or snake_case consistently:
totalMarksortotal_marks - Keep names reasonably short but descriptive
- Use prefixes for related groups:
btnSubmit,txtName
Types of Variables in C (Based on Scope)
Variables in C can be classified based on where they are declared, which determines their scope (visibility) and lifetime.
1. Local Variables
Local variables are declared inside a function or block. They can only be accessed within that block and are destroyed when the block finishes executing.
#include <stdio.h>
void greet() {
int x = 10; // local to greet()
printf("x inside greet: %d\n", x);
}
int main() {
int y = 20; // local to main()
printf("y inside main: %d\n", y);
greet();
// printf("%d", x); // ERROR! x is not visible here
return 0;
}y inside main: 20 x inside greet: 10
2. Global Variables
Global variables are declared outside all functions, typically at the top of the file. They are accessible from any function in that file.
#include <stdio.h>
int globalVar = 100; // global variable
void display() {
printf("Global variable in display(): %d\n", globalVar);
}
int main() {
printf("Global variable in main(): %d\n", globalVar);
globalVar = 200; // modifying global variable
display();
return 0;
}Global variable in main(): 100 Global variable in display(): 200
3. Static Variables
Static variables retain their value between function calls. They are initialized only once and exist for the entire program lifetime.
Count: 1 Count: 2 Count: 3
Without static, the variable count would be re-initialized to 0 every time the function is called.
4. Extern Variables
The extern keyword declares a variable that is defined in another file. It tells the compiler "this variable exists somewhere else — don't allocate memory for it here."
// file1.c
int sharedValue = 42; // definition
// file2.c
extern int sharedValue; // declaration (no memory allocated)
void printValue() {
printf("Shared: %d\n", sharedValue);
}5. Register Variables
Register variables are stored in CPU registers instead of RAM for faster access. The register keyword is a *hint* to the compiler — it may or may not honor it.
0 1 2 3 4
Note: You cannot take the address of a register variable using &.Comparison Table: Types of Variables
| Property | Local | Global | Static | Extern | Register |
|---|---|---|---|---|---|
| Scope | Within block | Entire file | Within block | Across files | Within block |
| Lifetime | Block execution | Program lifetime | Program lifetime | Program lifetime | Block execution |
| Default value | Garbage | 0 | 0 | 0 | Garbage |
| Storage | Stack | Data segment | Data segment | Data segment | CPU register |
| Declaration | Inside function | Outside all functions | With static keyword | With extern keyword | With register keyword |
Scope of Variables in C
Scope determines where in the program a variable can be accessed. C has three main types of scope:
Block Scope
Variables declared inside { } are only visible within those braces.
#include <stdio.h>
int main() {
int a = 5;
{
int b = 10; // block scope
printf("a = %d, b = %d\n", a, b); // both visible
}
printf("a = %d\n", a); // only a is visible
// printf("b = %d\n", b); // ERROR: b is out of scope
return 0;
}a = 5, b = 10 a = 5
Function Scope
Only labels (used with goto) have function scope in C — they're visible throughout the entire function regardless of block nesting.
File Scope
Variables declared outside all functions have file scope — they're visible from the point of declaration to the end of the file.
Common Mistakes with Variables
- Using uninitialized variables — always initialize before use
- Name conflicts — a local variable with the same name as a global variable *shadows* the global one
- Exceeding scope — trying to use a variable outside its declared block
- Using keywords as variable names —
int,for,whileare reserved
Interview Questions on Variables in C
Q1: What is the difference between declaration and definition of a variable?
Declaration tells the compiler about the variable's type and name. Definition allocates memory for it. In C, int x; is both a declaration and definition. extern int x; is only a declaration.
Q2: What happens if you use a variable without initializing it?
Local variables contain garbage values (unpredictable data). Global and static variables are automatically initialized to zero.
Q3: Can two variables have the same name in C?
Yes, if they are in different scopes. A local variable with the same name as a global variable will *shadow* the global variable within its scope.
Q4: What is the difference between static and global variables?
Both have program-wide lifetime, but their scope differs. A global variable can be accessed from any function in the file (and other files with extern). A static local variable can only be accessed within its function. A static global variable is restricted to its file only.
Q5: Why should we avoid using too many global variables?
Global variables make code harder to debug, test, and maintain. Any function can modify them unexpectedly, leading to hard-to-find bugs. They also increase memory usage since they exist for the program's entire lifetime.
Summary
- Variables are named memory locations that store data which can change during execution.
- Every variable must be declared with a data type before use.
- C supports local, global, static, extern, and register variables.
- Scope determines where a variable is accessible; lifetime determines how long it exists.
- Always initialize variables before using them to avoid garbage values.
- Follow naming conventions for readable and maintainable code.
- Understanding variable scope and lifetime is essential for writing bug-free C programs.
Exam Focus
Revise definitions, diagrams, examples, and short-answer points for Variables in C Programming.
Interview Use
Prepare one clear explanation, one practical example, and one common mistake for this C Programming topic.
Search Terms
c-programming, c programming, programming, basics, variables, variables in c programming
Related C Programming Topics