Variables
Programs need to remember things: a student's marks, the price of an item, the number of tickets left. In C you store each value in a variable, a named piece of memory that holds a value of one fixed type.
In this lesson you will declare variables, give them starting values, change them, and learn the naming rules and the mistakes that trip up most beginners.
Declaring and initialising variables
Before you use a variable in C, you must declare it: say its type and its name. You usually also initialise it, which means giving it a first value in the same line.
#include <stdio.h>
int main(void)
{
int age = 19;
double height = 1.68;
char section = 'B';
printf("Age: %d years\n", age);
printf("Height: %.2f m\n", height);
printf("Section: %c\n", section);
return 0;
}Age: 19 years Height: 1.68 m Section: B
Each declaration has the shape type name = value;:
intholds whole numbers such as 19 or -5.doubleholds numbers with a decimal point, such as 1.68.charholds a single character written in single quotes, such as'B'.
To print a variable, put a format specifier inside the printf text and pass the variable after it: %d for int, %f for double (here %.2f for two decimal places) and %c for char. You will meet all the types in Data Types & bool and all the specifiers in Input & Output.
The type is fixed for the life of the variable. Once age is an int, it can never hold text or a decimal number. This is called static typing, and it lets the compiler catch many mistakes before your program runs.
Changing a variable
The = sign is the assignment operator. It does not mean "equals" as in maths; it means "store the value on the right into the variable on the left". The right side is worked out first, so a variable can appear on both sides.
#include <stdio.h>
int main(void)
{
int runs = 0; // start of the over
runs = runs + 4; // a boundary
runs = runs + 1; // a single
runs = runs + 6; // a six
printf("Runs in the over: %d\n", runs);
runs = 0; // a new over begins
printf("Runs after reset: %d\n", runs);
return 0;
}Runs in the over: 11 Runs after reset: 0
Notice that only the declaration line has the type int. Later lines just use the name. Writing int runs = 0; a second time in the same block is an error, because the name already exists there.
Naming rules
Variable names, and all other names you create in C, are called identifiers. They must follow these rules:
- Use only letters, digits and the underscore
_. - Do not start with a digit:
marks2is fine,2marksis not. - Do not use a keyword, a word that C reserves for itself, such as
int,return,if,for,while,charordouble. - Names are case-sensitive:
total,TotalandTOTALare three different variables. - Avoid names that start with an underscore followed by a capital letter, or with two underscores. They are reserved for the compiler and the standard library.
Most C programmers write variable names in lowercase with underscores between words, such as ticket_price or total_marks. Choose names that say what the value means. days_late is much clearer than d.
Always initialise your variables
A variable declared inside a function without a value is uninitialised. C does not set it to zero for you. It holds whatever bits happened to be in that memory, and reading it is a bug.
#include <stdio.h>
int main(void)
{
int total; // bug: no starting value
total = total + 50; // adds 50 to an unknown value
printf("Total: %d\n", total);
int fixed_total = 0; // correct: start from zero
fixed_total = fixed_total + 50;
printf("Fixed total: %d\n", fixed_total);
return 0;
}The first printf could print 50, a huge number, or something different on every run. Reading an uninitialised variable is undefined behaviour, which means the C standard makes no promise at all about what happens. With -Wall, GCC warns that 'total' is used uninitialized. The habit to build is simple: give every variable a value when you declare it.
Swapping two values
A classic exercise is to swap the values of two variables. You cannot simply write a = b; b = a;, because the first line overwrites a and its old value is lost. Use a temporary variable to hold one value while you move the other.
#include <stdio.h>
int main(void)
{
int left = 7; // Priya's seat number
int right = 12; // Farhan's seat number
printf("Before: left = %d, right = %d\n", left, right);
int temp = left;
left = right;
right = temp;
printf("After: left = %d, right = %d\n", left, right);
return 0;
}Before: left = 7, right = 12 After: left = 12, right = 7
Here temp is declared in the middle of main, right where it is first needed. Modern C allows this, and it keeps each variable close to the code that uses it.
Type inference with auto (C23)
#include <stdio.h>
int main(void)
{
auto students = 42; // int
auto fee = 1250.50; // double
auto letter = 'K'; // int, not char!
printf("%d students pay Rs %.2f each\n", students, fee);
printf("letter uses %zu bytes\n", sizeof letter);
return 0;
}42 students pay Rs 1250.50 each letter uses 4 bytes
The last line surprises many people. In C, a character constant such as 'K' has type int, so auto makes letter an int, which is 4 bytes on common systems, not a 1-byte char. (sizeof gives the size of a variable in bytes, and %zu prints that size; you will meet both again soon.) For this reason most C programmers still write the type explicitly and keep auto for long, complicated type names. In older C, auto meant something else: it marked a normal local variable, which is the default anyway, so you will rarely see it in old code.
Common mistakes
- Using a variable before declaring it. The compiler reads from top to bottom and reports
'marks' undeclared. - Forgetting to initialise. Start counters and totals at 0 every time.
- Declaring the same name twice in one block. You get a "redefinition" error. Assign a new value instead.
- Spaces or hyphens in names.
total marksandtotal-marksare not valid names; usetotal_marks. - Mixing up
=and==.=stores a value;==compares two values. You will use==in if, else if & else.
Key points
- A variable is a named piece of memory with a fixed type; declare it as
type name = value;. =assigns: it works out the right side and stores the result in the variable on the left.- Names use letters, digits and underscores, cannot start with a digit and cannot be keywords.
- Local variables are not set to zero automatically; always initialise them.
- Declare variables close to where you use them (allowed since C99).
- C23
autoinfers a type from the initial value, but'K'givesint, so explicit types are often clearer.
Exercise
A tiffin service in Pune charges Rs 85 per meal. Aarav orders lunch for 22 working days and pays a delivery charge of Rs 150 for the month. Write a program with the variables price_per_meal, days, delivery and total. Calculate the total, print it, then change days to 20 (two holidays), recalculate total and print it again.
Show solution
#include <stdio.h>
int main(void)
{
int price_per_meal = 85;
int days = 22;
int delivery = 150;
int total = price_per_meal * days + delivery;
printf("Bill for %d days: Rs %d\n", days, total);
days = 20;
total = price_per_meal * days + delivery;
printf("Bill for %d days: Rs %d\n", days, total);
return 0;
}Bill for 22 days: Rs 2020 Bill for 20 days: Rs 1850
total does not update by itself when days changes. A variable stores a value, not a formula, so you must calculate total again after changing days.
Quick Quiz
1. What does int marks; inside a function contain before you assign to it?
Local variables are not initialised automatically, so their starting value is unpredictable.
2. Which variable name is valid in C?
Names can use letters, digits and underscores, cannot start with a digit and cannot be keywords.
3. After int x = 5; x = x * 2 + 1;, what is the value of x?
The right side is worked out first using the old value: 5 × 2 + 1 = 11, which is then stored in x.
4. In C23, what type does auto c = 'A'; give c?
In C a character constant such as 'A' has type int, so auto infers int.
Learn C with a mentor
Free lessons get you started. Our Java, C & C++ Programming training adds real projects and code reviews from working developers.
- Project-based learning
- Mentor code reviews
- Free counselling call
