Dalla A alla Z passando per C - Robotica
Dalla A alla Z passando per C - Robotica
Dalla A alla Z passando per C - Robotica
You also want an ePaper? Increase the reach of your titles
YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.
Tabella 10.1: Scope e lifetime delle variabili.<br />
Classe Scope Lifetime<br />
extern globale <strong>per</strong>manente<br />
auto locale temporaneo<br />
static locale <strong>per</strong>manente<br />
register locale temporaneo<br />
Il tempo di vita è <strong>per</strong>manente <strong>per</strong> le variabili allocate staticamente, mentre è temporaneo <strong>per</strong><br />
le variabili allocate dinamicamente, che vengono rilasciate al termine dell’esecuzione del blocco<br />
in cui sono definite.<br />
#include <br />
int c1 = 1;<br />
void func() {<br />
int c3 = 3;<br />
static c4 = 1;<br />
}<br />
printf("func: c1 %d c3 %d c4 %d\n", c1, c3, c4);<br />
c4++;<br />
int main(int argc, char **argv)<br />
{<br />
int i;<br />
}<br />
printf("main: c1 %d\n", c1);<br />
for (i = 0; i < 5; i++) func();<br />
return 0;<br />
La variabile c1 è globale, allocata staticamente, e può essere utilizzata in tutto il file sorgente.<br />
La variabile c3 è allocata dinamicamente ogni volta che la funzione func viene richiamata e<br />
può essere utilizzata soltanto all’interno della funzione stessa. Per quanto riguarda la variabile<br />
c4, anche se è dichiarata all’interno della funzione func; può essere usata soltanto all’interno<br />
di tale funzione, ma essendo dichiarata static, essa è allocata staticamente, e quindi l’area di<br />
memoria ad essa associata non viene rilasciata quando la funzione termina. Questo <strong>per</strong>mette a<br />
tale variabile di conservare il proprio valore da una chiamata all’altra della funzione.<br />
Un esempio di esecuzione del programma è il seguente:<br />
main: c1 1<br />
func: c1 1 c3 3 c4 1<br />
func: c1 1 c3 3 c4 2<br />
func: c1 1 c3 3 c4 3<br />
func: c1 1 c3 3 c4 4<br />
103