Search code examples
cstructinitializationdefinition

I am trying to make a struct that references a variable within itself. How do i do this?


Here is the code:

int main()
{
    struct board
    {
        int length_x;
        int length_y;

        int board_size = length_x*length_y;
    };
    struct board chess_board ={
        8,8
    };
    return 0;
}

This returns the error

error: variable-sized object may not be initialized

I have made this a lot simpler that what I'm actually coding but all i want is when i make a struct it does that operation.


Solution

  • In C you may not initialize data members of a structure in the structure definition.

    So this structure definition

    struct board
    {
        int length_x;
        int length_y;
    
        int board_size = length_x*length_y;
    };
    

    is incorrect.

    You should write

    struct board
    {
        int length_x;
        int length_y;
    
        int board_size;
    };
    

    and then

    struct board chess_board ={ 8, 8, 64 };
    

    or for example

    struct board chess_board =
    { 
        .length_x = 8, .length_y = 8, .board_size = 64 
    };
    

    It would be better to introduce a constant like

    enum { N = 8 };
    

    and then write

    struct board chess_board =
    { 
        .length_x = N, .length_y = N, .board_size = N * N 
    };
    

    Or you could write a separate function that will initialize data members of an object of the structure type.

    For example

    void init_board( struct board *board, int n )
    {
        board->length_x = n;
        board->length_y = n;
        board->board_size = n * n;
    }
    

    and after declaration of n object of the structure stype you could call the function

    struct board chess_board;
    init_board( &chess_board, 8 );