Int vs Float vs Double in C: Key Differences and Usage
int stores whole numbers without decimals, float stores single-precision decimal numbers, and double stores double-precision decimal numbers with more accuracy. Use int for integers, float for less precise decimals, and double when you need more decimal precision.Quick Comparison
Here is a quick table comparing int, float, and double in C based on key factors.
| Factor | int | float | double |
|---|---|---|---|
| Type of Data | Whole numbers (integers) | Decimal numbers (single precision) | Decimal numbers (double precision) |
| Size (typical) | 4 bytes | 4 bytes | 8 bytes |
| Precision | Exact for integers | Approx. 6-7 decimal digits | Approx. 15-16 decimal digits |
| Range | -2,147,483,648 to 2,147,483,647 | ±1.5 × 10⁻⁴⁵ to ±3.4 × 10³⁸ | ±5.0 × 10⁻³²⁴ to ±1.7 × 10³⁰⁸ |
| Use Case | Counting, indexing | Less precise decimals | High precision decimals |
| Memory Usage | Less | Moderate | More |
Key Differences
int is used to store whole numbers without any decimal part. It is exact for integers within its range and uses less memory compared to floating-point types.
float stores decimal numbers but with limited precision (about 6-7 digits). It uses 4 bytes and is suitable when you need decimals but can tolerate some rounding errors.
double stores decimal numbers with double the precision of float (about 15-16 digits) and uses 8 bytes. It is best when you need more accurate decimal calculations, like in scientific computations.
Code Comparison
#include <stdio.h> int main() { int a = 5; float b = 5.1234567f; double c = 5.123456789012345; printf("int a = %d\n", a); printf("float b = %.7f\n", b); printf("double c = %.15f\n", c); return 0; }
Double Equivalent
#include <stdio.h> int main() { double x = 3.141592653589793; printf("Double value: %.15f\n", x); return 0; }
When to Use Which
Choose int when you need to store whole numbers like counts, indexes, or flags without decimals. Use float when you want to save memory and only need approximate decimal values, such as in graphics or simple calculations. Opt for double when precision matters, like in scientific calculations, financial data, or when rounding errors must be minimized.
Key Takeaways
int for exact whole numbers without decimals.float for decimal numbers with moderate precision and less memory use.double for high precision decimal numbers and scientific calculations.