4.3Characters as integers and size_t pitfalls
The idea
A char is a small integer, so you can add, subtract and compare characters. Library lengths are unsigned.
Think of it like this: Letters are numbers on a ruler: 'a' is at 97, 'A' at 65, and the distance between a letter and its capital is always 32.
Why it exists
Character arithmetic ('7' − '0', c − 'a' + 'A') and the unsigned strlen difference both appear in exams.
How it works
- Remember anchors: '0' = 48, 'A' = 65, 'a' = 97.
- digit char − '0' gives the digit; lowercase − 32 gives uppercase.
- Chars are promoted to int in arithmetic.
- size_t (from strlen or sizeof) is unsigned: x − y with y > x wraps to a huge number.
Worked example: (strlen("abc") − strlen("defgh")) > 0
3 − 5 in unsigned arithmetic is 264 − 2, a huge positive number. The comparison with 0 is true, so the conditional expression picks strlen(s) = 3.
Now play with it
- →In the lab compute d − '0' and c − 'a' + 'A'.
- →Run the unsigned strlen difference program: the first line prints 1, the casted version −2.
Characters are small integers. 'a' = 97, 'A' = 65, '0' = 48, 'P' = 80, 'x' = 120.
Memory (one box per element, address below)
Gold = the object the expression names. Blue = the element a pointer result points to. Each box stands for one element; real addresses grow by sizeof(element).
strlen returns an unsigned type, so 3 − 5 wraps to a huge positive number and the comparison with 0 is true. Casting to int first gives the expected −2.
1#include <stdio.h>2#include <string.h>3int main() {4 char *x = "abc", *y = "defgh";5 unsigned int c = 0;6 printf("%d\n", (strlen(x) - strlen(y)) > c);7 printf("%d\n", (int)strlen(x) - (int)strlen(y));8 return 0;9}
The gold line is the statement about to run.
Call stack (top first)
Output
Check yourself
What is 'a' - 'A'?
Exam notes (the dense version)
A char is a small integer: 'A' = 65, 'a' = 97, '0' = 48, so 'a' − 'A' = 32 and c − '0' converts a digit. Arithmetic and bitwise operators on chars first promote them to int. strlen and sizeof give size_t, an unsigned type, so strlen(a) − strlen(b) never goes negative: it wraps to a huge positive number.
Previous year questions: Strings & Characters (3)
PYQs are grouped by topic, so this is the full set for Strings & Characters; try the ones that match this subtopic. Open all 3 on the topic page.