C Data Types
A data type in C tells the compiler what kind of value a variable can store. The type also affects how much memory the value uses and what operations make sense for it.
Why Types Matter
C is a typed language. That means every variable must have a type before it can store data. In the previous lesson, you used int for whole numbers. C also has types for decimal numbers, single characters, and more specialized values.
Choosing the right type helps the program store data correctly. For example, an age can usually be an int, but a price often needs a decimal type such as double.
Common Basic Types
| Type | Stores | Example value | Common printf specifier |
|---|---|---|---|
int |
Whole numbers | 42 |
%d |
float |
Decimal numbers | 3.5f |
%f |
double |
Decimal numbers with more precision | 19.99 |
%f |
char |
One character | 'A' |
%c |
A float literal often uses an f suffix, such as 3.5f. Without the suffix, a decimal literal such as 3.5 is treated as a double.
Example: Using Several Types
This program declares variables with several different types and prints them with matching format specifiers.
#include <stdio.h>
int main(void)
{
int students = 28;
float temperature = 21.5f;
double price = 14.99;
char grade = 'A';
printf("Students: %d\n", students);
printf("Temperature: %.1f\n", temperature);
printf("Price: %.2f\n", price);
printf("Grade: %c\n", grade);
return 0;
}
Output:
Students: 28
Temperature: 21.5
Price: 14.99
Grade: A
How The Example Works
The variable students is an int, so it stores a whole number and is printed with %d.
The variable temperature is a float. The format %.1f prints one digit after the decimal point.
The variable price is a double. The format %.2f prints two digits after the decimal point, which is useful for simple money examples.
The variable grade is a char. Character values use single quotes, such as 'A', and are printed with %c. Double quotes create a string, not a single char.
Checking Type Sizes
The sizeof operator tells you how many bytes a type or variable uses on your system. The result has type size_t, so it is commonly printed with %zu.
#include <stdio.h>
int main(void)
{
printf("char: %zu byte\n", sizeof(char));
printf("int: %zu bytes\n", sizeof(int));
printf("float: %zu bytes\n", sizeof(float));
printf("double: %zu bytes\n", sizeof(double));
return 0;
}
Output:
char: 1 byte
int: 4 bytes
float: 4 bytes
double: 8 bytes
The exact size of some types can vary between systems, but sizeof(char) is always 1. On many modern systems, int is 4 bytes, float is 4 bytes, and double is 8 bytes.
Picking A Type
- Use
intfor ordinary whole numbers. - Use
doublefor most decimal calculations unless you have a reason to usefloat. - Use
charfor one character. - Use the matching
printfspecifier for the type you print.
The key idea is that a variable’s type controls what kind of data it can safely store. Next, you will learn how constants let you name values that should not change.
