3

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**
3
  • 1
    static const int RMH_ENCODED_MSG_OVERHEAD = sizeof(EBD_HEAD) + sizeof(EBD_TRAIL); This compile fine. Don't know why. Commented May 17, 2011 at 11:14
  • @taskinoor:Yeah i did as you told and it works.But i have 7 to 8 such declarations and so i replaced with macro as epatel asked me to do Commented May 17, 2011 at 11:35
  • @ron, yes the answer of epatel is better. Mine is not even an answer. I am just curious what is happening here. Commented May 17, 2011 at 11:47

2 Answers 2

2

Use macros instead.

#define EBD_HEADER_SIZE sizeof(EBD_HEAD)
#define EBD_TRAILER_SIZE sizeof(EBD_TRAIL)
#define RMH_ENCODED_MSG_OVERHEAD (EBD_HEADER_SIZE + EBD_TRAILER_SIZE)

Feels scary? Read this and remember this is C (which Objective-C is based on) and not C++

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks a lot for making me to understand about macros.
2

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 enums; 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.

1 Comment

Thanks alaster for explaining me clearly about enums and macros.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.