Here are 3 ways to solve the problem without using a table of constants.
1) Char pointer for constant string:
#include <stdlib.h>
#include <stdio.h>
int main( int argc, char * argv[] )
{
char * nome_lanche = NULL;
int preco_lanche = 0;
int cod_lanche = atoi( argv[1] );
switch( cod_lanche )
{
case 0:
nome_lanche = "macarrao";
preco_lanche = 10;
break;
case 100:
nome_lanche = "hamburger";
preco_lanche = 5;
break;
default:
nome_lanche = "invalido";
preco_lanche = -1;
break;
}
printf("Codigo: %d\n", cod_lanche );
printf("Nome: %s\n", nome_lanche );
printf("Preco: %d\n", preco_lanche );
return 0;
}
/* fim-de-arquivo */
2) Static memory allocation (chars vector):
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#define NOME_MAX_TAM (100)
int main( int argc, char * argv[] )
{
char nome_lanche[ NOME_MAX_TAM + 1 ] = {0};
int preco_lanche = 0;
int cod_lanche = atoi(argv[1]);
switch( cod_lanche )
{
case 0:
strcpy( nome_lanche, "macarrao" );
preco_lanche = 10;
break;
case 100:
strcpy( nome_lanche, "hamburger");
preco_lanche = 5;
break;
default:
strcpy( nome_lanche, "codigo invalido" );
preco_lanche = -1;
break;
}
printf("Codigo: %d\n", cod_lanche );
printf("Nome: %s\n", nome_lanche );
printf("Preco: %d\n", preco_lanche );
return 0;
}
/* fim-de-arquivo */
3) Dynamic allocation of memory:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main( int argc, char * argv[] )
{
char * nome_lanche = NULL;
int preco_lanche = 0;
int cod_lanche = atoi(argv[1]);
switch( cod_lanche )
{
case 0:
nome_lanche = strdup("macarrao");
preco_lanche = 10;
break;
case 100:
nome_lanche = strdup("hamburger");
preco_lanche = 5;
break;
default:
nome_lanche = strdup("codigo invalido");
preco_lanche = -1;
break;
}
printf("Codigo: %d\n", cod_lanche );
printf("Nome: %s\n", nome_lanche );
printf("Preco: %d\n", preco_lanche );
free( nome_lanche );
return 0;
}
/* fim-de-arquivo */
I hope I’ve helped!
Then I should create a constant table and use strcpy inside the switch?
– Bruno Wosniak
Using a constant table will not use strings and can use
switch
. If you’re going to use strings, then you’ll have to useif
withstrcmp()
.– Maniero