C Variables
A variable in C is a named storage location for a value. Variables matter because they let a program remember information, reuse it, update it, and combine it with other values while the program runs. In C, every variable has a type, so the compiler knows how much memory to reserve and how the stored bits should be interpreted.
Overview: How Variables Work
When you declare a variable, you give the compiler two important facts: the variable’s type and its name. The type controls what kind of value the variable can hold, such as an int for whole numbers, a double for decimal numbers, or a char for one character. The name is the identifier you use later in the program.
At runtime, a variable usually corresponds to bytes of memory. For example, an int often uses 4 bytes, although the C standard allows the exact size to vary by system. Those bytes do not know that they are an age, a score, or a count. The type tells the compiler how to generate instructions for reading, writing, and calculating with those bytes.
A variable’s value can be changed by assignment. In score = 15;, the expression on the right is evaluated first, then the resulting value is stored into the variable on the left. If score already had a value, the old value is replaced. This is why variables are called variable: their contents can vary while the program executes.
C does not automatically give every local variable a safe starting value. A local variable declared inside a function without an initializer has an indeterminate value until you assign to it. Reading that value is a serious bug. For beginner code, the practical rule is simple: initialize variables when you declare them unless you have a clear reason to assign them immediately afterward.
Syntax
int count = 3;
double price = 19.95;
char grade = 'A';
| Part | Meaning |
|---|---|
int, double, char |
The variable type. It decides the allowed values, memory size, and operations. |
count, price, grade |
The variable name, also called an identifier. |
= |
The assignment operator. In a declaration, it gives the variable its initial value. |
3, 19.95, 'A' |
The value stored in the variable. |
; |
Ends the declaration statement. |
You may declare a variable without initializing it, as in int count;, but you must assign a value before reading it. You can also declare several variables of the same type in one statement, such as int x = 1, y = 2;, though separate declarations are often clearer for beginners.
Examples
Declaring, Initializing, and Printing
#include <stdio.h>
int main(void)
{
int age = 21;
double height = 1.75;
char initial = 'M';
printf("Age: %d\n", age);
printf("Height: %.2f meters\n", height);
printf("Initial: %c\n", initial);
return 0;
}
Output:
Age: 21
Height: 1.75 meters
Initial: M
This program creates three variables with three different types. The printf format specifiers must match the variable types: %d prints an int, %.2f prints a floating-point value with two digits after the decimal point, and %c prints a character.
Updating a Variable
#include <stdio.h>
int main(void)
{
int score = 10;
printf("Starting score: %d\n", score);
score = score + 5;
printf("After bonus: %d\n", score);
score = score - 2;
printf("After penalty: %d\n", score);
return 0;
}
Output:
Starting score: 10
After bonus: 15
After penalty: 13
The statement score = score + 5; may look strange at first because it is not an equation. C evaluates the right side using the current value of score, producing 15, and then stores 15 back into score.
Using Variables in a Calculation
#include <stdio.h>
int main(void)
{
int notebooks = 4;
double price_each = 2.50;
double subtotal = notebooks * price_each;
double tax = subtotal * 0.08;
double total = subtotal + tax;
printf("Notebooks: %d\n", notebooks);
printf("Subtotal: $%.2f\n", subtotal);
printf("Tax: $%.2f\n", tax);
printf("Total: $%.2f\n", total);
return 0;
}
Output:
Notebooks: 4
Subtotal: $10.00
Tax: $0.80
Total: $10.80
Variables become most useful when they participate in expressions. Here, subtotal, tax, and total each store the result of a calculation. If notebooks or price_each changes, the later calculations can be updated without rewriting the whole program.
How It Works Step by Step
- The compiler reads a declaration such as
int score = 10;and records thatscoreis anintin the current block. - It checks later uses of
score. If you try to use an undeclared name, the compiler reports an error. - When the program runs, storage is made available for the variable. For ordinary local variables, this storage is typically part of the function’s stack frame.
- The initializer
10is stored in that storage before the next statement uses the variable. - When an expression reads
score, the program loads its current value. When an assignment writesscore, the program stores a new value in the same named location.
The variable’s scope is the region of code where its name can be used. A variable declared inside main is not visible outside main. Its lifetime is how long its storage exists. Most local variables exist only while their block is executing.
Common Mistakes
Reading an Uninitialized Local Variable
A declaration such as int total; creates the variable, but it does not give a local variable a reliable value. The corrected version initializes total before printing it.
#include <stdio.h>
int main(void)
{
int total = 0;
printf("Total: %d\n", total);
return 0;
}
Output:
Total: 0
Redeclaring Instead of Reassigning
After a variable has already been declared in a block, update it with its name only. Do not write the type again in the same block.
#include <stdio.h>
int main(void)
{
int level = 1;
level = 2;
printf("Level: %d\n", level);
return 0;
}
Output:
Level: 2
Using the Wrong Format Specifier
The variable type and the printf specifier must agree. Use %d for int, %f for double, and %c for char.
#include <stdio.h>
int main(void)
{
int count = 7;
double average = 8.5;
printf("Count: %d\n", count);
printf("Average: %.1f\n", average);
return 0;
}
Output:
Count: 7
Average: 8.5
Best Practices
- Initialize local variables when you declare them, especially in beginner code.
- Use descriptive names such as
student_countortotal_pricewhen the meaning is not obvious. - Use lowercase names with underscores for ordinary variables; this is common in C code.
- Keep each variable’s scope as small as practical by declaring it near where it is first used.
- Choose a type that matches the data: use integer types for counts, floating-point types for measured decimal values, and
charfor single characters. - Match
printfformat specifiers to the variable types you print. - Compile with warnings enabled, such as
-Wall -Wextra, because compilers can catch many variable-related mistakes.
Practice Exercises
- Create an
intvariable namedbooks, initialize it to3, add2to it, and print the result. - Write a program with
doublevariables for a product price and discount. Print the final price with two digits after the decimal point. - Create variables for a student’s first initial, number of completed lessons, and average score. Print each value on its own labeled line.
Summary
- A C variable is a named storage location with a specific type.
- Declarations tell the compiler a variable’s type and name.
- Initialization gives a variable its first value; assignment replaces its current value.
- Local variables should not be read before a value has been stored in them.
- Variables can be used in expressions, calculations, and function calls such as
printf. - Clear names, correct types, and matching format specifiers make variable code easier to read and safer to compile.
