In C, you can only by scalar constants in switch
. A string is a pointer variable, so we will have difficulties using this method exactly.
In Stackoverflow in English, who replied suggested that a hash
function is used to be able to use switch
with the string; or use the so-called "ladder" if-else
.
Wikipedia has a entry explaining hash functions . A function of hash
for a generic string can be defined like this (I will not null-safe
):
int hash_function(char *str) {
int acc = 0;
int peso = 1;
int base = 256;
int len = strlen(str);
int modulus = 65000;
int i;
for (i = 0; i < len; i++) {
int char_at = str[i]; /* char é um número de 8 bits, enquanto que int é um número de 16 ou 32 bits, dependendo do compilador */
acc = (acc*base + peso*char_at) % modulus;
peso = (peso % 10) + 1; /* peso varia de 1 a 10 */
}
return acc;
}
Having the function of hash
pre-determined, we already know what the value of "School" can be and creating the HASH_ESCOLA
macro:
int tratar_escola(char *lugar) {
int hash_lugar = hash_function(lugar);
switch (hash_lugar) {
case HASH_ESCOLA:
/* vamos checar se deu positivo verdadeiro? */
if (strcmp(lugar, "Escola") == 0) {
printf("Estudar\n");
return 1;
}
}
return 0;
}
An algorithm of hash
/ scattering algorithm can generate collisions ( Wikipedia article ), which in this case is another object that returns the same value as its desired object. To avoid colliding with a value other than Escola
, I make the comparison with the original string.