How do I store variables so they retain their values, like for highscores?

Previous Memory, C Variables, and Pointers Next

Q: How do you store preferences, high scores, and suchlike so that they do not go away when you exit the program? I have absolutely no clue how to do this.
A: The simplest method is: if you stored preferences in an array, declare this array as "static". For example,
static int high_scores[10] = {};
In this case, such array will be kept in the program file itself (instead on the stack), so it will not go away after you exit the program. This method has only one drawback: preferences will not be kept if the program is archived.

Be aware of the initializer: static variables must be initialized in the "nostub" mode. An empty initializer in this example is equivalent to the
static int high_scores[10] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
Don't be confused which such initialization. It seems that the array elements will be set back to 0 any time when you run the program. But, this is not true. The initialization of automatic and static variables is quite different. Automatic (local) variables are initialized during the run-time, so the initialization will be executed whenever it is encountered in the program. Static (and global) variables are initialized during the compile-time, so the initial values will simply be embeded in the executable file itself. If you change them, they will retain changed in the file.