Friday, March 25, 2011

Storage and linkage specifiers - The static keyword

I'll be reviewing from now on c/c++ and linux programming topics, as I might be working in the near future in a hydrology project involving a real time application for linux that'll be crunching a big load of numbers, yay!!.

  • The static keyword defines variables that live as long the program is executing, only one copy of such variables is kept. The part that caught my attention is the case when they're declared inside of a function, they live and retain their value after the function is exited, cool! Scope rules are still applicable.


[sourcecode language="cpp"]
#include <iostream>
#include <stdlib.h>
using namespace std;
int small_val(void){
static unsigned count;
count++;
cout<<"Call to small_val number: "<<count<<endl;
return (count % 16);
}
void r_func(void){
static int depth;
depth++;
if(depth > 200){
cout<<"Excessive recursion \n"<<endl;
exit(EXIT_FAILURE);
}
else{
small_val();//cout<<"count in small_val has the value: "<<count<<endl; <-invalid
r_func();
}
depth--;
}
int main(void){
r_func();
}
[/sourcecode]

Source:

http://publications.gbdirect.co.uk/c_book/chapter4/linkage.html

No comments:

Post a Comment