Róbert Nagy
Róbert Nagy

Reputation: 7602

Array declaration inside struct using predefined constant in C++

I want to declare an array inside a structure with a predefined constant size, but it gives me this error : expected a ']'.

#define MAX_SZAMJEGY 200;

struct szam {

    int szj[MAX_SZAMJEGY];
    bool negative;
};

Upvotes: 1

Views: 94

Answers (3)

SergeyA
SergeyA

Reputation: 62563

A preferred C++ solution is to use constants rather than macros. This way you will not have a semicolon problem, and it comes with tons of other benefits as well. Here is how:

(C++ 98):

static const size_t MAX_SZAMJEGY 200;

struct szam {

    int szj[MAX_SZAMJEGY];
    bool negative;
};

(C++11)

static constexpr size_t MAX_SZAMJEGY=200;

struct szam {

    int szj[MAX_SZAMJEGY];
    bool negative;
};

And while you are on it, and if you are using C++11, you might as well replace C-style array with C++ std::array. While it doesn't make too much of a difference, it is slightly more convenient to use.

Upvotes: 4

Starl1ght
Starl1ght

Reputation: 4493

Macro expands to

int szj[200;]; 

which is not valid C++ code.

remove ; from #define MAX_SZAMJEGY 200;

Upvotes: 5

gbehar
gbehar

Reputation: 1299

try

#define MAX_SZAMJEGY 200

instead of

#define MAX_SZAMJEGY 200;

(the semicolon enters the macro)

Upvotes: 2

Related Questions