items[…]
is subsetting the array items
.
(int)(type - '1')
is calculating the index to use for subsetting.
(int)(…)
is a cast to int
. It’s worth noting that this cast is completely unnecessary here: the result of subtracting two character values (or an integer from a character) already yields the type int
in C due to integer promotion. This means that we can rewrite the expression to
items[type - '1']
Lastly, type - '1'
subtracts the numeric character code of the character constant '1'
from the numeric character code of the value in variable type
. The result of this transformation is that if type
is '1'
, the value of type - '1'
is 0, if type
is '2'
the value is 1, and so on.
Alternatively, the code could be implemented as follows:
char type_str[2] = { type };
int choice = atoi(type_str) - 1;
printf("\nYou've selected %s\n", items[choice]);
This makes it perhaps slightly clearer that we’re translating a character value into an integer value. However, it’s actually a much more complex implementation:
- we first need to construct a string from the character (by assigning it into an array and zero-terminating the string, which happens implicitly in the initialisation of
type_str
above)
- then we invoke
atoi
to translate "1"
into 1, "2"
into 2, …
- the we subtract 1, to get a zero-based index.
In the end, this isn’t more readable or less error-prone — neither for beginners nor for expert C programmers.
In a more realistic application, it’s conceivable that the user input was directly a string rather than a character, which makes the application of atoi
more useful. We’d also potentially want to handle errors (what happens if the user entered an invalid value? The current code — both mine and the one you posted — happily attempt to subset the array after an invalid input, with potentially bad consequences).