Statement and initialization of struct outside the main function in C

1

I'm doing a little game in C that has the letter structure:

typedef struct {
    int numero;
    int cor;
} TipoCarta;

A method for placing the values in the chart:

void inicializaCarta(TipoCarta *carta, int num, int cor){
    carta->numero = num;
    carta->cor = cor;   
}

And in main I will have to declare and initialize each card by passing the values, for example:

TipoCarta amarelo1, amarelo2;
inicializaCarta(&amarelo1, 1, amarelo); 
inicializaCarta(&amarelo2, 2, amarelo);

(in the header has a constant defining an integer for yellow)

Is it possible to boot into another .c file, or at least off main? Pro code does not get so "polluted" since it will have many letters.

    
asked by anonymous 12.06.2018 / 02:10

1 answer

2

If the problem is pollution, you could rewrite your main() in a different way, see:

typedef enum { corVermelho, corAzul, corVerde, corAmarelo } TipoCor;

typedef struct {
    int numero;
    TipoCor cor;
} TipoCarta;

void inicializaCarta( TipoCarta * carta, int num, TipoCor cor ){
    carta->numero = num;
    carta->cor = cor;
}

int main( void ) {
    int i = 0;

    TipoCarta amarelo[10];
    TipoCarta azul[10];
    TipoCarta verde[10];
    TipoCarta vermelho[10];

    for( i = 0; i < 10; i++ ) {
        inicializaCarta( &vermelho[i], i + 1, corVermelho );
        inicializaCarta( &azul[i], i + 1, corAzul );
        inicializaCarta( &verde[i], i + 1, corVerde );
        inicializaCarta( &amarelo[i], i + 1, corAmarelo );
    }

    return 0;
}

In the example above,% with% of% color_cards% were initialized, totaling% with_cards%.

Alternatively, you can put your 10 within 4 , see:

typedef enum { corVermelho, corAzul, corVerde, corAmarelo } TipoCor;

typedef struct {
    int numero;
    TipoCor cor;
} TipoCarta;

typedef struct {
    TipoCarta amarelo[10];
    TipoCarta azul[10];
    TipoCarta verde[10];
    TipoCarta vermelho[10];
} TipoDeck;

void inicializaCarta( TipoCarta * carta, int num, TipoCor cor ){
    carta->numero = num;
    carta->cor = cor;
}

void inicializaDeck( TipoDeck * deck )
{
    int i = 0;

    for( i = 0; i < 10; i++ ) {
        inicializaCarta( &deck->vermelho[i], i + 1, corVermelho );
        inicializaCarta( &deck->azul[i], i + 1, corAzul );
        inicializaCarta( &deck->verde[i], i + 1, corVerde );
        inicializaCarta( &deck->amarelo[i], i + 1, corAmarelo );
    }
}

int main( void )
{
    TipoDeck deck;
    inicializaDeck( &deck );
    return 0;
} 
    
12.06.2018 / 02:45