Search code examples
c++arraysclassstaticinitialization

How to initialize array out of the class and set a value to the first element?


Use in Arduino. The problem is there: Player::coords[0] = {0, 0};

Heading file:

#ifndef game_h
#define game_h
#include <Arduino.h>

class Player {
  public:
    int getScore();
    static int coords[3250][2];
    coordinates: x, y

  private:
    static int score;
};

#endif

Cpp file:

#include "game.h"

int Player::score = 1;

int Player::getScore() {
  return this->score;
}

int Player::coords[3250][2];
Player::coords[0] = {0, 0};

Compiler writes: 'coords' in 'class Player' does not name a type


Solution

  • You may not do this way at a namespace scope

    int Player::coords[3250][2];
    Player::coords[0] = {0, 0};
    

    In fact these statements are equivalent to this one

    int Player::coords[3250][2] = { { 0, 0 } };
    

    or

    int Player::coords[3250][2] = {};
    

    or even just

    int Player::coords[3250][2];
    

    because the array has the static storage duration and zero-initialized by the compiler.