C course menu
Variables in C: Declaration, Initialization, Assignment and Scope Basics
Learn C variables: declaring and initialising variables, assignment, uninitialised variables and why they are dangerous, declaring several variables, naming rules, and printing variables with printf.
On this page
A variable is a named piece of memory that holds a value. In C, every variable has a type, decided when you declare it, which fixes what kind of value it can hold and how much memory it uses.
Declaring and initialising#
#include <stdio.h>
int main(void) {
int age = 21; /* declare and initialise */
double price = 49.99;
char grade = 'A';
printf("Age: %d\n", age);
printf("Price: %.2f\n", price);
printf("Grade: %c\n", grade);
return 0;
}Age: 21
Price: 49.99
Grade: AThe pattern is type name = value;. The format specifier in printf must match the type: %d for int, %f for double, %c for char.
Assignment#
After declaring a variable, you can change its value with =:
int score = 10;
score = 15;
score = score + 5;
printf("%d\n", score);20score = score + 5 reads the current value (15), adds 5, and stores the result back.
Uninitialised variables#
A local variable declared without a value contains whatever happened to be in that memory. Reading it is a bug, and its value is unpredictable:
int total; /* not initialised: holds garbage */
total = total + 5; /* bug: the result is unpredictable */Always initialise variables when you declare them, even if only to 0. With -Wall, GCC warns about many uses of uninitialised variables.
Several variables at once#
int x = 1, y = 2, z = 3;
printf("%d\n", x + y + z);6Be careful: int a, b = 0; initialises only b. One declaration per line avoids this trap.
Where to declare#
Since C99, you can declare variables anywhere in a block, close to where they are used, including in a for loop header. A variable exists only inside the block where it is declared (its scope):
int outer = 1;
{
int inner = 2;
printf("%d %d\n", outer, inner);
}
/* inner does not exist here */
printf("%d\n", outer);1 2
1Scope and storage classes are covered in Scope and Storage Classes.
Naming variables#
- Use descriptive names:
total_price, nottp. snake_caseis the most common style in C.- Names are case-sensitive and cannot start with a digit or be keywords (Syntax).
Practice#
Practice exercise
Declare variables for a product's quantity (3) and unit price (149.50). Print the total with two decimal places, then change the quantity to 5 and print the new total.
Show solution
#include <stdio.h>
int main(void) {
int quantity = 3;
double unit_price = 149.50;
printf("Total: %.2f\n", quantity * unit_price);
quantity = 5;
printf("Total: %.2f\n", quantity * unit_price);
return 0;
}Total: 448.50
Total: 747.50Key takeaway#
Finished this lesson?