C - Datatypes
C provides fundamental types like char
, int
, float
, and double
, plus modifiers like short
, long
, and unsigned
.
Learning Objectives
- Choose appropriate types for different values and ranges.
- Understand signed vs unsigned and size modifiers.
- Use
sizeof
to determine type sizes.
Prerequisites
Basic Types
#include <stdio.h>
int main(void) {
char c = 'A'; // typically 1 byte
int i = 42; // typically 4 bytes
float f = 3.14f; // typically 4 bytes
double d = 3.141592653589793; // typically 8 bytes
printf("char: %c (size: %zu)\n", c, sizeof(c));
printf("int: %d (size: %zu)\n", i, sizeof(i));
printf("float: %.2f (size: %zu)\n", f, sizeof(f));
printf("double: %.15f (size: %zu)\n", d, sizeof(d));
}
Modifiers
#include <stdio.h>
#include <limits.h>
int main(void) {
short s = 32000;
long l = 2000000000L;
unsigned int u = 4000000000U;
long long ll = 9000000000000LL;
printf("short: %d (range: %d to %d)\n", s, SHRT_MIN, SHRT_MAX);
printf("unsigned: %u (range: 0 to %u)\n", u, UINT_MAX);
printf("long long: %lld\n", ll);
}
Common Pitfalls
- Integer overflow wraps around for unsigned types but is undefined for signed.
- Comparing signed and unsigned values can give unexpected results.
- Using wrong format specifiers for printf (e.g.,
%d
forlong
).
Checks for Understanding
- What's the difference between
float
anddouble
? - What happens when an
unsigned char
exceeds 255? - How do you print a
long long
?
Show answers
- Precision and range:
double
typically has more precision and wider range. - It wraps to 0 (well-defined for unsigned types).
- Use
%lld
format specifier.
Practice
- Choose appropriate types for: age, bank balance, pixel color (0-255), population count.
- Use
sizeof
to print the size of each basic type on your system.