Search code examples
c++arraysconstantschess

array bound is not an integer constant before ']' token


main:

#include <iostream>
#include "common.h"
#include "squares.h"
#include "board.h"
using namespace std;
int Board::board_length=8;
int main()
{
    Board *tabla=new Board();
    tabla->printBoard();
}

board.h :

#ifndef BOARD_H
#define BOARD_H
#include "squares.h"

class Board
{
   static int board_length;
   Square boardSquares[board_length][board_length];
   public:
   Board();
   void printBoard();

};

error line 8 in board.h C:\c++ projects\CHESS-P3\board.h|8|error: array bound is not an integer constant before ']' token|


Solution

  • As the error message indicates, board_length is not a constant value. To fix that, change the line

    static int board_length;
    

    in board.h to

    static const int board_length = 8;
    

    and remove the line

    int Board::board_length=8;
    

    from your main file. This should compile, but I cannot tell for sure, since you did not provide a minimal, reproducible example.

    Bonus: To avoid a memory leak you should also change

    Board *tabla=new Board();
    tabla->printBoard();
    

    in main just to

    Board tabla;
    tabla.printBoard();
    

    Since you do not seem to be passing the Board instance around, there is no need to use a pointer here.

    As a general rule of thumb: Whenever there is a new somewhere, there also needs to be a corresponding delete. Otherwise your pogram may leak memory. While this is no big deal for a small, short-running example program, it can become a serious issue for a program that runs for a long time.