Evandro Filipe
Evandro Filipe

Reputation: 71

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.

Upvotes: 1

Views: 99

Answers (2)

tstanisl
tstanisl

Reputation: 14117

You could use a macro to make a smart initializer

#define BOARD_INIT(N) { (N), (N), (N) * (N) }

struct board b = BOARD_INIT(8);

In C99 you could use compound literal and designated initializer to add some type-safety as well

#define BOARD_INIT(N) (struct board) { \
  .length_x = (N),                     \
  .length_y = (N),                     \
  .board_size = (N) * (N)              \
}

Actually, it is possible to make a "self-reference" because the name of the initialized variable is visible inside the initializer list.

struct board b = {
  .length_x = 8,
  .length_y = 8,
  .board_size = b.length_x * b.length_y,
};

According to 6.7.9p19:

The initialization shall occur in initializer list order the values of b.length_x and b.length_y should be ready when b.board_size is initialized.

Upvotes: 0

Vlad from Moscow
Vlad from Moscow

Reputation: 310980

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

Upvotes: 2

Related Questions