In C, variables must be declared with a specific data type. The data type tells the compiler how much memory to allocate for the variable and what kind of values it can securely hold.
Choosing the right data type is crucial for memory efficiency and ensuring your program behaves correctly. C provides several basic (built-in) data types.
Here are the most common basic data types used in C:
| Data Type | Description | Size (typical) | Example | Format Specifier |
|---|---|---|---|---|
int |
Stores whole numbers (integers), without decimals. | 4 bytes | int age = 25; |
%d or %i |
float |
Stores fractional numbers containing a decimal point. Sufficient for storing 6-7 decimal digits. | 4 bytes | float pi = 3.14f; |
%f |
double |
Stores fractional numbers containing a decimal point. Sufficient for storing 15 decimal digits. | 8 bytes | double precisePi = 3.1415926535; |
%lf |
char |
Stores a single character, letter, number, or ASCII value. Enclosed in single quotes. | 1 byte | char initial = 'A'; |
%c |
int)The int data type is used to store positive and negative whole numbers.
#include <stdio.h>int main() { int items = 50; int negativeTemp = -15;
printf("Number of items: %d\n", items); printf("Temperature is: %d\n", negativeTemp);
return 0; }
You can modify the int type to optimize memory usage if you know the exact range of values your variable will hold:
short int (usually 2 bytes)long int (usually 4 or 8 bytes)long long int (usually 8 bytes)float and double)Use float or double when you need to store numbers with decimals.
A float offers single precision, while a double provides double precision. If you need highly accurate calculations (like scientific data or financial applications), double is the preferred choice, although it takes up twice as much memory.
#include <stdio.h>int main() { float myFloat = 9.99f; double myDouble = 19.99;
// Notice the format specifiers: %f for float, %lf for double printf("Float value: %f\n", myFloat); printf("Double value: %lf\n", myDouble);
return 0; }
Note: It's a common practice to append an 'f' to a float literal (e.g., `3.14f`). If you omit the 'f', the compiler might treat the literal as a double by default.
char)The char data type is used to store a single character. The character must be surrounded by single quotes, like 'A' or 'c'.
Under the hood, C stores characters as integer values based on the ASCII table. For example, the character 'A' is stored as the number 65.
Which format specifier is used to print a `double` variable?