Thursday, July 9, 2009

How does the static variable i work in the following C code fragment and what will the output be?

void main (void) {


while (next()%26lt;1000);


}





int next (void) {


static int i =500;


int j =10;





printf (j, i++,"\n");


return (i);


}





I don't need an exact output, just an idea of how it will look and how "static" actually works.





thanks!

How does the static variable i work in the following C code fragment and what will the output be?
The static variable i is essentially a global variable, but it has scope restricted to the "next" function.





This means that the first time "next()" is invoked, i is initialized to 500. On subsequent calls to "next()", the variable i is not re-initialized and retains its value from the previous call. The "i++" increments i by one each function call. On the other hand, the variable j is a normal local variable and is re-initialized to 10 every time the function is called. This means the output will be something like:





10 500


10 501


10 502


10 503


10 504


...


10 999
Reply:A static variable is effectively a constant http://www.space.unibe.ch/comp_doc/c_man...

florist delivery

No comments:

Post a Comment