Tip for C code optimization

Asked

Viewed 464 times

5

The way I wrote the code below is very extensive. How to make the code more streamlined?

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 wish I didn’t have to loop for each vector. There will be several vectors.

2 answers

7


Optimizing is different from shortening.

This code looks very artificial and little can be done. You can organize more, make it cleaner.

You can take comments that have no function in it.

You can shorten it using some syntactic rules, but I don’t really like doing that.

You can declare variable where you will already use and save a line.

What more could give some gain is to put the loop in a function that treats the 2 vectors. In fact it will not even shorten, but will leave without repetition.

If you want to sweep a vector you have to have a loop. You can put it in other places. Eventually I could change the output function to reverse 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;
    }
}

I put in the Github for future reference.

4

Instead of passing the array elements one by one, pass the array (converted to a pointer for the first element) and its size at once.

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]);
    }
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.