I’ve messed with characters as values quite a few times in my code. Keeping in mind that the char data type is really a tiny integer value, you can perform all kinds of tricks — stuff that drives non-programmers crazy.
For example, I often do math using character values. Consider that char variable a
is a digit, 0 through 9:
b = a - '0';
This statement subtracts character '0'
from the value of variable a
. Seems crazy, but what’s really going on is the ASCII code value for '0'
(48 decimal, 0x30 hex) is subtracted from variable a
. Because variable a
holds a digit, the result is the value 0 through 9, which is stored in variable b
. This technique is one way to convert character numbers into their integer values.
Likewise, you can convert a letter of the alphabet to an integer value 0 through 26 for A through Z:
b = a - 'A';
All this nonsense works because to the computer, a character is really a visual representation of a value. This interpretation leads to some interesting possibilities, as shown in the following code.
2021_08_07-Lesson.c
#include <stdio.h> int main() { int t['A']; printf("The array contains %ld elements\n",sizeof(t)/sizeof(int)); return(0); }
At Line 5, int array t[]
is defined, which contains 'A'
elements. This statement is valid in C because the 'A'
is converted by the compiler into its integer value. To see how many elements are in the array, run the program:
The array contains 65 elements
If you look up the value of 'A'
on an ASCII table (see this month’s Exercise), you discover that it’s 65. So the declaration int t['A']
creates an array of 65 elements, the ASCII value of character 'A'
.
By the way, the array size is determined by dividing the amount of memory occupied by the array, sizeof(t)
, by the size of the array’s data type, integer sizeof(int)
. The result yields the number of elements in the array.
Using characters as integers is a fun trick, one that can throw off a beginning C programmer. The problem with this trick is that it obfuscates the code. It’s much easier to write int t[65]
than int t['A']
. But it’s cute, so I thought I’d point it out.