C is the equivalent of a static Java block (runs once at startup)

I found many answers to this question in C ++, but I'm very interested in C.

I have a circular linked list in C and I want to initialize it with a dummy node header before it is first available. A dummy node header is a statically assigned global variable. This is my current solution:

static once = 1; if(once){ once = 0; // Setup code } 

This works, but I have to put it in every function that uses this linked list. (Of course, I can put this code in my own function, so I only need to call this function in any other function, but this is not much better). Is there a better way? For example, if I have the following structure:

 struct node { int value; struct node *next; } 

Is it possible to initialize one of these structures as a literal so that its next value points to itself?

In the Initialize as Literal section, I mean the following: (Sorry, probably the wrong terminology)

 struct test { int i; double d; }; struct test magic = {1, 2.3}; // This can just be done at the top of the c file, outside of any functions int someFunction(){...} 
+7
c static
source share
1 answer

You can just do what you say and point to yourself if it is a file scope variable:

 #include <stdio.h> struct node { int value; struct node * next; }; struct node mylist = { 1, &mylist }; int main(void) { printf("%d %d\n", mylist.value, mylist.next->value); return 0; } 

with output:

 paul@horus :~/src/sandbox$ ./list 1 1 paul@horus :~/src/sandbox$ 

You can, of course, add the β€œrun once at startup” code to main() before doing anything else, and achieve the same goal:

 #include <stdio.h> #include <stdlib.h> struct node { int value; struct node * next; }; struct node * mylist; int main(void) { mylist = malloc(sizeof *mylist); if ( !mylist ) { perror("couldn't allocate memory"); return EXIT_FAILURE; } mylist->value = 1; mylist->next = mylist; /* Rest of your program here */ return 0; } 
+5
source share

All Articles