[cs631apue] questions about openmax.c

Sadia Akhter sakhter at stevens.edu
Wed Sep 17 00:03:59 EDT 2014


When we define a variable within a function as static, that variable is initialized once during the execution of the program and the value in that variable persists between function calls. For example, suppose we have following code:

void count() 
{
	int val  = 0;
	static int countVal = 0;
	++countVal;
	++val;
	printf("%d %d\n", countVal, val);
} 

int main() 
{
	count();
	count();
	return 0;
}

The output will be:
1 1
2 1

The reason is that the variable countVal is initialized to 0 exactly once during the program execution and it's value persists between function calls. When count() is called for the first time from main(), val is initialized to 0, countVal is also initialized to 0, both values are increased by 1 and the values are printed. Thats why we get "1 1" as output. When count() return, the local variable val is destroyed but the static variable countVal exists and holds the current value, which is 1.

Second time the function count() is called from main(), the local variable val is initialized to 0 (again!) but countVal is not initialized. It holds the value it got from the previous function call. So when the variables are incremented, val holds 1 where countVal holds 2. So when we print the values we get "2 1".

Sadia



On Sep 16, 2014, at 6:01 PM, zding4 <zding4 at stevens.edu> wrote:

> Hi everyone:
> 
> Sorry if you guys think this may be a trivial question
> When I read the source code of openmax.c
> It defines a static int variable openmax
> 
> ----------------------------------------
> #ifdef OPEN_MAX
> 	static int openmax = OPEN_MAX;
> #else
> 	static int openmax = 0;
> #endif
> ----------------------------------------
> 
> Why is it the "static int"?
> 
> 
> 
> _______________________________________________
> cs631apue mailing list
> cs631apue at lists.stevens.edu
> https://lists.stevens.edu/mailman/listinfo/cs631apue



More information about the cs631apue mailing list