Tip for code optimization in C

5

The way I wrote the code below is too long. How to make the code leaner?

void mostrasaida(char recebido)
{
    int dadoA [5] = {252, 146, 145, 146, 252};
    int dadoB [5] = {255, 201, 201, 201, 182};
    //Varios vetores de AaZ
    int cont=0;
    switch (recebido) //Pesquisa o caractere recebido e imprime
    {
        case 'A': //Se o caractere recebido for A
        for(cont=0; cont<5; cont++)//Gostaria de não ter que fazer esse laço para cada vetor.
        {
            saida (dadoA[cont]); //Envia
        }
        break;
        //----------------------------------------------------
        case 'B': //Se o caractere recebido for A
        for(cont=0; cont<5; cont++)//Então executa o laço for por cinco veses
        {
            saida (dadoB[cont]); //Envia
        }
        break;
    }
}

I'd like to not have to do the loop for each vector. For there will be several vectors.

    
asked by anonymous 26.07.2016 / 18:20

2 answers

7

Optimizing is different from shortening.

This code seems very artificial and very little can be done. You can organize more, leave cleaner.

You can take the comments that have no function in it.

You can shorten it by using some syntax rules, but I do not really like doing this.

You can declare a variable where you are going to use it and save a line.

What else could give some gain is to place the loop in a function that treats the 2 vectors. In fact neither will shorten, but will leave without repetition.

If you want to scan a vector you have to have a loop. You can go in other places. Eventually I could change the output function to get this, but it would be less generic.

void varreVetor(int vetor[5]) {
    for(int cont = 0; cont < 5; cont++) saida(vetor[cont]);
}
void mostrasaida(char recebido) {
    int dadoA[5] = {252, 146, 145, 146, 252};
    int dadoB[5] = {255, 201, 201, 201, 182};
    switch (recebido) {
        case 'A':
            varreVetor(dadoA);
            break;
        case 'B':
            varreVetor(dadoB);
            break;
    }
}
    
26.07.2016 / 18:31
4

Instead of passing the array elements one by one, it passes the array (converted to a pointer to the first element) and its size at one time.

switch (recebido) {
    case 'A': saida_completa(dadoA, sizeof dadoA / sizeof *dadoA);
              break;
    case 'B': saida_completa(dadoB, sizeof dadoB / sizeof *dadoB);
              break;
    default:  /* erro */
              break;
}

Inside the function you loop. The function would be anything like

void saida_completa(int *a, int n) {
    for (int i = 0; i < n; i++) {
        saida(a[i]);
    }
}
    
26.07.2016 / 18:36