Reputation: 755
I am getting "Initializer Element is not a constant" error for the following declaration.
struct EBD_HEADER
{
char x;
int Key;
char Number;
int ID;
int Version;
}EBD_HEAD;
struct EBD_TRAILER
{
int Crc_0;
int Crc_1;
int Etx;
}EBD_TRAIL;
static const int EBD_HEADER_SIZE = sizeof(EBD_HEAD);
static const int EBD_TRAILER_SIZE = sizeof(EBD_TRAIL);
static const int RMH_ENCODED_MSG_OVERHEAD = EBD_HEADER_SIZE +
EBD_TRAILER_SIZE; //**error:Intializer Element is not a constant**
Upvotes: 3
Views: 127
Reputation: 4433
static const int
in C declares a variable of type int
whose value can be assumed (when optimising) not to change. It doesn’t declare a constant, unlike in C++.
If you want integer constants in plain C, you can either use macros as the previous answer suggests, or use an enum
instead. Note that you are allowed to use anonymous enum
s; e.g.
enum {
EBD_HEADER_SIZE = sizeof (EBD_HEAD),
EBD_TRAILER_SIZE = sizeof (EBD_TRAIL),
RMH_ENCODED_MSG_OVERHEAD = sizeof (EBD_HEAD) + sizeof (EBD_TRAIL)
};
Note that using enum
for this purpose is not without its problems; you can only declare constants of integral type this way, and if you decide to use a named enum
(either via a tag or via typedef
), it’s worth noting that some compilers will choose different sizes or alignments for your type according to the number and values of its member constants.
Obviously, using #define
also has a few drawbacks, not least the well-known problems of accidental multiple evaluation of side-effects and operator precedence.
Upvotes: 2