Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to initialize a const variable inside a struct in C?

I write a struct

struct Tree{
    struct Node *root;
    struct Node NIL_t;
    struct Node * const NIL;    //sentinel
}

I want

struct Node * const NIL = &NIL_t;

I can't initialize it inside the struct. I'm using msvs.

I use C, NOT C++. I know I can use initialization list in C++.

How to do so in C?

like image 204
Celebi Avatar asked Jan 13 '11 01:01

Celebi


People also ask

Can we use const inside structure?

No, using const in such a way is not a good idea. By declaring your structure fields as const , you are declaring an intention that those fields will never change their value.

How do you initialize a const variable?

To initialize the const value using constructor, we have to use the initialize list. This initializer list is used to initialize the data member of a class. The list of members, that will be initialized, will be present after the constructor after colon. members will be separated using comma.

Can we initialize variable in structure in C?

Structure members cannot be initialized with declaration.

Can const be applied on structure objects?

'const' as the word constant itself indicates means unmodifiable. This can be applied to variable of any data type. struct being a user defined data type, it applies to the the variables of any struct as well. Once initialized, the value of the const variables cannot be modified.


2 Answers

If you are using C99, you can used designated initializers to do this:

struct Tree t = { .root = NULL, .NIL = &t.NIL_t };

This only works in C99, though. I've tested this on gcc and it seems to work just fine.

like image 108
templatetypedef Avatar answered Oct 30 '22 22:10

templatetypedef


For those seeking a simple example, here it goes:

#include <stdio.h>

typedef struct {
    const int a;
    const int b;
} my_t;

int main() {
   my_t s = { .a = 10, .b = 20 };
   printf("{ a: %d, b: %d }", s.a, s.b);
}

Produces the following output:

{ a: 10, b: 20 }
like image 31
Erik Campobadal Avatar answered Oct 31 '22 00:10

Erik Campobadal