Declaring variables
- C course
- Beginner
- Lesson 7/116
- 4 min
Learn to declare variables of type int, double, char and float.
Declaring variables
In C, a variable is a named memory location that stores a value. To declare a variable, you write the type first, then the name:
int age = 25;
double height = 1.75;
char letter = 'A';Common types: int (integer), double (decimal), char (character), float (single-precision decimal). You can assign the value at declaration or later.
Multiple variables
You can declare multiple variables of the same type in a single line:
int a = 1, b = 2, c = 3;Or assign the value later:
int x;
x = 10;Local variables declared without an initial value are uninitialized; always assign before reading. As a good practice, give a value at the moment of declaration.
Practice Declare and print a variable
Declare an int variable, give it a value, and print it with printf using the %d specifier.
Starter code
// declare an int variable and print itSample solution
#include <stdio.h>
int main(void) {
int age = 25;
printf("%d", age);
return 0;
}Expected output
25
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Which is an integer type?
- double
- char
- void
- int Correct answer
Explanation: int is the type used for integers.
2 Assignment operator
int age ____ 25;
int age = 25;
Explanation: The = operator assigns a value.
3 Match the types
| Term | Meaning |
|---|---|
int |
Integer |
double |
Decimal |
char |
Character |
float |
Single precision |