Explain it simply
Explain it simply
A variable is like a labelled box that holds data. In C you must declare the box's shape, its data type, before you use it, because the compiler needs to know how much memory to set aside and how to read the bits inside. An int box holds whole numbers, a double box holds decimal numbers and a char box holds a single character.
You can swap what is inside the box as often as you like, but you can never change the box's shape. One more thing matters a lot: C does not clean a new box for you. Until you put a first value in, it may contain whatever junk was left behind.
Problem → Why → Solution
The problem: a total that was never set
This program declares total, adds 5 to it and prints the result. You might expect Total: 5. One test run printed Total: 32764, and other compilers, settings or machines can print other numbers. Compiled without flags, GCC gave no warning at all; only with -Wall did it report "'total' is used uninitialized".
In a real program this could be a running price, a counter or a sensor average, and it might look correct on the developer's machine and be wrong on a customer's.
#include <stdio.h>
int main(void) {
int total; /* declared, but never given a value */
total = total + 5;
printf("Total: %d\n", total);
return 0;
}Why isn't a new variable zero?
A variable declared inside a function gets its memory each time the function runs. Filling that memory with zeros would cost time, so C does not do it; the bits left from earlier use are still there. The standard calls the value indeterminate, and reading it in total + 5 is undefined behavior. The fix costs nothing: write int total = 0; so every variable is born with a first value.
Core concept: named memory with a type, a value and a scope
A variable is a named piece of memory with a fixed type. The declaration int age = 20; does three things at once: it tells the compiler the name age, it fixes the type as int, which decides how many bytes are set aside and how the bits are read, and it initializes the memory with 20. The type can never change afterwards; age holds an int for as long as it exists.
Initialization and assignment look alike but happen at different times. Initialization gives the first value as part of the declaration. Assignment, such as age = 21;, replaces the value later, and the variable must already be declared. The = sign does not mean "is equal to"; it means "store the value on the right into the variable on the left". That is why age = age + 1; makes sense: read age, add one, store the result back. Comparison uses == and comes in the Operators lesson.
| Type | What it holds | printf |
|---|---|---|
| int | Whole numbers such as -3, 0, 42 | %d |
| double | Numbers with a fraction, about 15 significant digits | %f, %.2f |
| float | Smaller, less precise decimals (about 7 digits), written 19.99f | %f |
| char | One character such as 'A' (a small integer code) | %c |
A variable declared inside a function without an initializer does not start at zero; as the problem section showed, its value is indeterminate. Other languages hide this behind a default value or an error, and C does neither.
Finally, a variable exists from its declaration to the closing brace of the block that contains it. That region is its scope. Outside it the name is unknown and the memory may be reused. Declaring variables in the smallest block that needs them keeps them close to where they are used and stops other code from changing them by accident.
Three variables after the example runs
--------------------------------------
name type value
+-------+---------+--------------+
| age | int | 20 -> 21 | assignment replaced the value
| price | double | 19.99 |
| grade | char | 'A' -> 'B' | the type never changes
+-------+---------+--------------+- Declare: pick a name and a type
- Initialize: put the first value in
- Assign: replace the value with =
- Scope ends at the block's closing }
The box's shape (its type) is fixed for good; only the contents change. A box that looks empty is never empty in C: it holds leftover bits until you put a value in.
General pattern
type name; /* declaration only: value not set yet */
type name = value; /* declaration with initialization */
name = new_value; /* assignment: change it later */
type first = 1, second = 2; /* several variables of the same type */
{
type inner = value; /* visible only inside this block */
}Avoid the first form without an initializer: if you do not know the first value yet, use 0. An assignment does not repeat the type; writing the type again would declare a new variable instead.
Example: three variables and two assignments
The program declares three variables of different types, initializes them immediately and prints each with its matching specifier. Two assignments then change the values; notice that they replace the contents of the same boxes instead of creating new variables.
#include <stdio.h>
int main(void) {
int age = 20;
double price = 19.99;
char grade = 'A';
printf("Age: %d\n", age);
printf("Price: %.2f\n", price);
printf("Grade: %c\n", grade);
age = age + 1; /* assignment: same variable, new value */
grade = 'B';
printf("Next year: %d, new grade: %c\n", age, grade);
return 0;
}Code breakdown
- Line 4
int age = 20;Declaration and initialization in one statement: memory for an int is set aside and 20 is stored in it straight away.
- Line 5
double price = 19.99;A literal such as 19.99 is a double, so it fits a double variable with no conversion. If you want a float, write float price = 19.99f; with the f suffix.
- Line 6
char grade = 'A';A char holds one character, written in single quotes. In memory it is stored as the character's integer code.
- Line 9
printf("Price: %.2f\n", price);%.2f shows the double with two digits after the decimal point, which suits prices. The specifier must match the variable's type.
- Line 12
age = age + 1; /* assignment: same variable, new value */The right side is evaluated first: read age (20), add 1, then store 21 back into age. There is no int in front, so this is not a new variable.
- Line 14
printf("Next year: %d, new grade: %c\n", age, grade);Two specifiers pair with two arguments in order, and the variables now show their updated values, 21 and B.
Age: 20
Price: 19.99
Grade: A
Next year: 21, new grade: Bfloat versus double
double is C's default floating type: a literal such as 19.99 is a double. A float uses half the memory on most systems but keeps only about 7 significant digits. At two decimal places both print 19.99, but asking for ten decimals reveals the float's rounding error. Prefer double unless memory is tight, and when you do use float, add the f suffix, as in 19.99f, so the literal matches. float price = 19.99; also works, because the double literal is converted to float, but the suffix states your intent.
#include <stdio.h>
int main(void) {
float price_f = 19.99f;
double price_d = 19.99;
printf("%.2f %.2f\n", price_f, price_d); /* 19.99 19.99 */
printf("%.10f\n", price_f); /* 19.9899997711 */
printf("%.10f\n", price_d); /* 19.9900000000 */
return 0;
}Scope in action
Below, bonus exists only inside the inner braces. count is declared in main's block, so the inner block can read and change it, and it still exists after the block ends. Try to use bonus after the closing brace and GCC reports "'bonus' undeclared (first use in this function)". Variables declared outside every function have file scope and live for the whole run; the real-world section looks at the price of that convenience.
#include <stdio.h>
int main(void) {
int count = 1;
{
int bonus = 10; /* exists only inside these braces */
count = count + bonus;
printf("inside: count=%d bonus=%d\n", count, bonus);
}
/* bonus is gone here; using it would be a compile error */
printf("outside: count=%d\n", count);
return 0;
}In real projects
How this shows up in real projects
Embedded firmware reads a sensor into a variable many times per second and decides whether to switch on a fan. Choosing the type is a real design decision there: an int counter of milliseconds will overflow eventually, and a float may not be precise enough for money. C codebases usually name variables in snake_case, such as retry_count or max_users, and many style guides ask for one declaration per line so each variable can carry its own comment.
Teams also keep variables local. A global variable, declared outside every function, can be changed by any function in the program, which creates hidden dependencies: one function's result depends on what other code did earlier, tests interfere with each other, and with threads two parts of the program can write it at the same time. Compiler flags such as -Wall -Wextra and tools such as Valgrind and Clang's MemorySanitizer help catch reads of uninitialized variables before they ship.
Common mistakes
Common mistakes
1. Reading a variable before giving it a value
Like total in the problem section, the value is indeterminate, and -Wall does not always catch it: in a test where an uninitialized sum was updated inside a loop, GCC gave no warning unless -O2 was also on. Initialize every variable where you declare it.
2. Declaring the same name twice in one block
Writing int score = 10; and later int score = 20; makes GCC report "redefinition of 'score'" with a note pointing at the "previous definition of 'score' with type 'int'". To change the value, write an assignment without the type: score = 20;.
3. Storing a decimal in an int
int price = 19.99; compiles and stores 19: the fraction is cut off silently, not rounded. -Wall -Wextra say nothing; -Wconversion warns "conversion from 'double' to 'int' changes value". Use double for values that need decimals.
4. Using a variable outside its block
A variable declared inside a block is gone after the closing brace, so using bonus from the scope section outside its block is an undeclared error. If you still need the value after the block, declare the variable outside the block and assign to it inside.
Mini challenge
Mini challenge: a wallet tracker
Track an item count, a balance and a currency letter with three variables, and print them before and after a purchase.
- Declare and initialize an int item count (0), a double balance (5000.00) and a char currency letter ('K')
- Print the starting values with the matching specifiers
- Buy 2 items at 1250.50 each, updating the variables with assignments rather than new declarations
- Print the new values, with the balance shown to two decimal places
#include <stdio.h>
int main(void) {
// TODO: declare and initialize three variables:
// an int for the item count (start at 0),
// a double for the balance (start at 5000.00),
// a char for the currency letter ('K' for kyat)
// TODO: print "Start: ..." using %d, %.2f and %c
// TODO: buy 2 items at 1250.50 each by ASSIGNING new values
// (do not declare the variables again)
// TODO: print "After shopping: ..." with the updated values
return 0;
}Expected: Two lines like these: Start: 0 items, balance 5000.00 K After shopping: 2 items, balance 2499.00 K
Show hint
The right side of an assignment may use the variable's old value, as in items = items + 2;. A printf with three specifiers needs three arguments in the same order.
Show solution
#include <stdio.h>
int main(void) {
int items = 0;
double balance = 5000.00;
char currency = 'K'; /* K for kyat */
printf("Start: %d items, balance %.2f %c\n", items, balance, currency);
items = items + 2;
balance = balance - 2 * 1250.50;
printf("After shopping: %d items, balance %.2f %c\n", items, balance, currency);
return 0;
}Quick quiz 1 / 3
Quick quiz 2 / 3
Quick quiz 3 / 3
What to remember
- A declaration gives a variable a name and a fixed type; initialization gives it a first value in the same statement.
- = assigns: it stores the right-hand value into the variable on the left, so age = age + 1; is valid.
- Use int for whole numbers, double for decimals and char for single characters, matched by %d, %f and %c in printf.
- Uninitialized local variables hold garbage, so initialize every variable where you declare it.
- A variable exists only inside the block where it is declared; keep that scope as small as possible.
GNU C compiler diagnostics — GNU Project