Home > Enterprise >  Char as Array index
Char as Array index

Time:06-21

Can someone explain me why the index of cvorkommen (zeichen_c - '0' works as an integer 4?

#include <stdio.h>
#include <string.h>

int main (void) {
  char cvorkommen [100] = {0};
  char zeichen_c = '4';

  cvorkommen[zeichen_c - '0']  
 
  return 0;
}

CodePudding user response:

For the 10 numeric digit characters the C standard requires them to be in sequence:

5.2.1 Character sets

3 ... In both the source and execution basic character sets, the value of each character after 0 in the above list of decimal digits shall be one greater than the value of the previous.

Other characters, such as alphabet letters, are not required to be in sequence. The uppercase and lowercase ASCII character alphabet characters are in sequence, but the EBCDIC ones are not.

So to find the numeric value of a digit character, it is always safe to subtract the base case

char digit = '4';
int number = digit - '0';

CodePudding user response:

That works because you take the char zeichen_c which has the ASCII value of '4' (0x34) and subtract the ASCII value of '0' (0x30) from it. That leaves you with 0x4 which is a valid index of your array.

  • Related