user3464679
user3464679

Reputation: 309

Initializing a struct in C : initializer element is not constant

I have read other answers on this topic, but they didn't help me. I am trying to initalize a struct but getting the following error msgs in C:

error: initializer element is not constant

error: (near initialization for 'resource01.resource.role')

For Url it works, it's just the role which is not working. And if I'm defining the role as char, I don't have any problems. What am I doing wrong?

static char const resource01Url[] = "/dummy";
static int const resource01Role = 2;
static struct RestResourceNode_S resource01 =
{
    {
        resource01Url,
        resource01Role,
        &DummyHandler_call
    },
    NULL
};

static struct RestResourcesManager_S resourcesManager =
{
    &resource01, &resource01
};

The type RestResourceNode_S is defined:

struct RestResourceNode_S
{
    RestResource_T resource;
    struct RestResourceNode_S const *next;
}

and RestResource_t:

struct RestResource_S
{
    char const *url;

    int const *role;

    retcode_t (*handle)(Msg_T *);
};

typedef struct RestResource_S RestResource_T;

Upvotes: 0

Views: 2489

Answers (1)

Chris
Chris

Reputation: 4231

The error means that you are using a non-constant expression to initialize a structure member.

The expression is resource01Role.

While it is declared as static and const it is not an initializer constant expression from the view of the C compiler. If you want to use it this way, you would have to define it as a preprocessor macro. In your case, const only points out to the compiler that the value of resource01Role will not change - it does not permit it to use the value during compile-time.

However, as @WhozCraig pointed out, the type of role is actually int const *, so you probably meant to write &resource01Role. Adress-of is a constant expression, so that would compile.

Since resource01Url is an array, the adress-of operator & is implicitly applied by the compiler, so it is constant.

Upvotes: 1

Related Questions