BzFr BzFr - 3 months ago 26
C Question

Const self-referential structures

I'm writing in C.

I've defined a new type (noFunc_menuEntry) which is made of a self-referential structure.

struct noFunc_menuEntry_tag {
const char *text;
struct noFunc_menuEntry_tag *up_entry;
struct noFunc_menuEntry_tag *down_entry;
struct noFunc_menuEntry_tag *back_entry;
struct noFunc_menuEntry_tag *enter_entry;
};
typedef struct noFunc_menuEntry_tag noFunc_menuEntry;


I need to define a series of variable like this:

menuEntry_1 = {title_1, &menuEntry_2, &menuEntry_4, &menuEntry_1, &menuEntry_5};
menuEntry_2 = {title_2, &menuEntry_3, &menuEntry_1, &menuEntry_1, &menuEntry_6};


and so on.

So i need to separate declaration and defition of the variable, because every variable depends on other variables. In an header file i've written the declaration

noFunc_menuEntry menuEntry_1, menuEntry_2, menuEntry_3, menuEntry_4, menuEntry_5, menuEntry_6;


etc..., and in a .c file in a function i've initialized the variables:

void menu_init(void)
{
menuEntry_1.text = title;
menuEntry_1.up_entry = &menuEntry_2
}


and so on for the other members and variables.

However i want my variables to be
const
:

const noFunc_menuEntry menuEntry_1, menuEntry_2, menuEntry_3, menuEntry_4, menuEntry_5, menuEntry_6;


So my question is about separing declaration and definition of
const
variables of the type i've defined. How can i do? Am i doing something wrong?

Naturally if i simply add
const
in the declaration, the compiler report me an error when i initialize the variables (i'm trying to write read-only variables).

Answer

If you want these variables to be const, then you must do the initialization without the function.

But first, let's handle the const in type definition:

typedef struct noFunc_menuEntry_tag noFunc_menuEntry;
struct noFunc_menuEntry_tag {
    const char *text;
    const noFunc_menuEntry *up_entry;
    const noFunc_menuEntry *down_entry;
    const noFunc_menuEntry *back_entry;
    const noFunc_menuEntry *enter_entry;
};

Then the declarations for the header file:

extern const noFunc_menuEntry menuEntry_1;
extern const noFunc_menuEntry menuEntry_2;
 ...

And finally the definition and initialization in source file:

const noFunc_menuEntry menuEntry_1 = {title_1, &menuEntry_2, &menuEntry_4, &menuEntry_1, &menuEntry_5};
const noFunc_menuEntry menuEntry_2 = {title_2, &menuEntry_3, &menuEntry_1, &menuEntry_1, &menuEntry_6};
 ...
Comments