persistent local variable in c

tarabyte picture tarabyte · Dec 5, 2010 · Viewed 13.5k times · Source

Are persistent variables not widely used? I couldn't find much info about them online or in the index of my C textbook - the Art and Science of C.

Anything you can share about them, especially their scope and example declaration would be helpful. I'm guessing to declare them you use 'persistent' as the keyword?

static void foo( void ) {
  persistent unsigned int width = 5;
}

This is the only other helpful reference I could find: “Persistent variables keep their state when the board is turned off and on, when main is run, and when system reset occurs. Persistent variables will lose their state when code is downloaded as a result of loading or unloading a file.” http://www.newtonlabs.com/ic/ic_5.html#SEC9

thanks!

Answer

jkerian picture jkerian · Dec 5, 2010

Interactive C (the link you provided) provides the persistent keyword, but that is not standard C. Particularly since guarantees like "keep their state when the board is turned off and on, when main is run, and when system reset occurs".

persistent is provided with the Interactive C compiler and works with dedicated hardware, Motorola chip in this case, storing the variable value in non-volatile memory to achieve persistence over restarts.

Interactive C is a C compilation environment for many Motorola 6811 based robots and embedded systems. Originally developed for the MIT LEGO Robot Design Contest (6.270), Interactive C has enjoyed widespread distribution and use. Interactive C's claim to fame is its interactivity: users can type in expressions and have them compiled on the fly and run immediately, rather than waiting for lengthy compile and download cycles. IC currently supports the 6.270, the HandyBoard and the RugWarrior and RugWarrior Pro. source.

To achieve variable persistence in a local scope (e.g. function), use the static keyword.