C Variables
C variables are named containers that store data in memory. In C every variable has a type, and you must declare that type before you use the variable.
Declaring and Initializing Variables
The syntax is type name = value;. Here int stores whole numbers, double stores decimals and char stores a single character.
#include <stdio.h>
int main(void) {
int age = 25;
double price = 9.99;
char grade = 'A';
printf("Age: %d\n", age);
printf("Price: %.2f\n", price);
printf("Grade: %c\n", grade);
return 0;
}Age: 25 Price: 9.99 Grade: A
Format Specifiers
printf cannot guess a variable's type, so you tell it with a format specifier inside the string.
- %d or %i for int
- %f for double (use %.2f for two decimals)
- %c for char
- %s for strings
- %zu for size_t values such as sizeof results
- %p for pointer addresses
Changing Variable Values
Assigning a new value replaces the old one. You can also declare several variables of the same type in one line.
#include <stdio.h>
int main(void) {
int x = 5, y = 10, z;
z = x + y;
x = 100; // overwrite x
printf("x=%d y=%d z=%d\n", x, y, z);
return 0;
}x=100 y=10 z=15
C Variable Naming Rules
- Names can contain letters, digits and underscores.
- A name must begin with a letter or an underscore, never a digit.
- Names are case-sensitive: total and Total are different variables.
- Reserved keywords like int, return and while cannot be used as names.
- Prefer descriptive names like itemCount or item_count over single letters.
Uninitialized Variables
A local variable that is declared but not given a value contains garbage, whatever bits were already in that memory. Reading it is undefined behavior, so always initialize variables before use.
Frequently asked questions
What happens if I use an uninitialized variable in C?
Its value is unpredictable and reading it is undefined behavior. Your program might print random numbers or behave differently each run. Always give variables a starting value.
What is the difference between declaration and initialization in C?
Declaration tells the compiler a variable's name and type (int x;). Initialization gives it its first value at the same time (int x = 5;).
Why does printf need %d?
printf receives raw values and uses the format specifier to know how to interpret and display each one. Using the wrong specifier gives wrong output or undefined behavior.