79152584

Date: 2024-11-03 11:26:13
Score: 0.5
Natty:
Report link

In C it is possible to create maps using lookup tables.
Here a example:

#include <stdio.h>

static int parse_numbers[] = {
    ['1'] = 'A',
    ['2'] = 'B',
    ['3'] = 'C'
};

int main(void) {
    printf("%c\n", parse_numbers['1']);
    printf("%c\n", parse_numbers['2']);
    printf("%c\n", parse_numbers['3']);

    return 0;
}

These are powerful to obtain exactly what you asked for. It works thanks enums.
In fact, the following syntax produces the same result (discouraged!):

#include <stdio.h>

enum numbers {
    number_1 = 1,
    number_2 = 2,
    number_3 = 3,
};

static int parse_numbers[] = {
    [number_1] = 'A',
    [number_2] = 'B',
    [number_3] = 'C'
};

int main(void) {
    printf("%c\n", parse_numbers['1']);
    printf("%c\n", parse_numbers['2']);
    printf("%c\n", parse_numbers['3']);

    return 0;
}

This syntax is very reluctant from changes. It is easy to make mistakes changing the enum or the struct. Please, stay away from this, use the first one.

Reasons:
  • Blacklisted phrase (0.5): thanks
  • Long answer (-0.5):
  • Has code block (-0.5):
  • Low reputation (1):
Posted by: Mass