C Variables
A variable in C is a named place in memory where a program can store a value. You choose the variable name, choose what kind of value it can hold, and then use that name later in the program.
Declaring Variables
Before you use a variable in C, you must declare it. A declaration tells the compiler the variable’s type and name.
int age;
This creates a variable named age that can store an integer value. The type int means whole numbers such as 5, 42, or -3.
Assigning Values
After declaring a variable, you can store a value in it with the assignment operator =. You can also declare and assign in one statement.
#include <stdio.h>
int main(void)
{
int age = 21;
printf("Age: %d\n", age);
return 0;
}
Output:
Age: 21
In the printf call, %d is a placeholder for an int value. The variable age is passed after the string, so its stored value is printed in that position.
Changing A Variable
A variable can be assigned a new value after it already has one. The old value is replaced.
#include <stdio.h>
int main(void)
{
int score = 10;
printf("First score: %d\n", score);
score = 15;
printf("Updated score: %d\n", score);
return 0;
}
Output:
First score: 10
Updated score: 15
Notice that the second assignment uses score = 15;, not int score = 15;. The variable was already declared, so you only write its name when giving it a new value.
Using More Than One Variable
Programs often use several variables at the same time. Each variable should have a name that describes what it stores.
#include <stdio.h>
int main(void)
{
int apples = 6;
int oranges = 4;
int total = apples + oranges;
printf("Apples: %d\n", apples);
printf("Oranges: %d\n", oranges);
printf("Total fruit: %d\n", total);
return 0;
}
Output:
Apples: 6
Oranges: 4
Total fruit: 10
The variable total stores the result of adding apples and oranges. When a variable appears in an expression, C uses the value currently stored in that variable.
Variable Names
C variable names must follow a few rules:
- They can contain letters, digits, and underscores.
- They must not start with a digit.
- They must not be a C keyword such as
intorreturn. - They are case-sensitive, so
scoreandScoreare different names.
Choose names like student_count, price, or total_score instead of vague names like x when the meaning matters.
Common Beginner Mistakes
- Declare a variable before using it.
- Use one
=for assignment. - Do not redeclare the same variable in the same block.
- Use the correct
printfplaceholder for the type you are printing.
The key idea is that variables let a C program remember values and reuse them. Next, you will learn more about C data types and the different kinds of values variables can store.
