From: ao950 AT FreeNet DOT Carleton DOT CA (Paul Derbyshire) Newsgroups: comp.os.msdos.djgpp Subject: Re: Static / Volatile Date: 3 Jan 1998 10:16:55 GMT Organization: The National Capital FreeNet Message-ID: <68l36n$ss@freenet-news.carleton.ca> References: <34ad01e2 DOT 2972639 AT news DOT dlc DOT fi> Reply-To: ao950 AT FreeNet DOT Carleton DOT CA (Paul Derbyshire) NNTP-Posting-Host: freenet5.carleton.ca Lines: 50 To: djgpp AT delorie DOT com DJ-Gateway: from newsgroup comp.os.msdos.djgpp Precedence: bulk (yorka AT dlc DOT fi) writes: > Could someone explain what the keywords 'static' and 'volatile' mean, > and what I would gain by using them? In a function, a static variable is instantiated at the start of execution, persists until the program ends, and remembers its value from one call to another, unlike normal local variables. However it is still local to the function. In C++, in a class, a static variable has only one instance shared by all instances of the class. It is a "class variable" instead of an "instance variable". The class header should include a declaration of the static variable, and an accompanying class .cc/.cpp file should include a definition. In C++, the above static variables in functions work the same way. A volatile variable is not cached in a register or optimized away by the compiler. Volatile is used on variables that can change "spontaneously" even when the current execution thread isn't touching it. This may be because an interrupt changes it, or it depends on a hardware function, like the VGA retrace, or you have written a multithreaded program and it may be changed in more than one thread. Basically, if it is possible for the code int x; x=5; // stuff that doesn't touch x if (x!=5) { // x was changed } to enter the if clause with the comment "x was changed", meaning x was altered by something independent of that chain of statements, then x should be declared volatile. The reason is because if x is located in memory at 0x5566, has the value 5, and gets cached in eax say, and then some other thread or an interrupt changes x to 6, then 0x5566 holds the 6, but eax still has the 5, and if the value is plucked from eax, it should be 6 now but isn't. Worse, it might have been cached elsewhere in edx, while eax gets saved and another thread runs. Then eax might be 5, 0x5566 might be 5, and edx might be 6, and you have even more versions of the same variable, with different values. If the variable is declared volatile, its value will always come from a memory location, e.g. 0x5566, and all parts of a program with threads or interrupts will agree on its value. -- .*. Friendship, companionship, love, and having fun are the reasons for -() < life. All else; sex, money, fame, etc.; are just to get/express these. `*' Send any and all mail with attachments to the hotmail address please. Paul Derbyshire ao950 AT freenet DOT carleton DOT ca pgd73 AT hotmail DOT com