static variable and initialization

When I create a static variable local to a function:
e.g.
void f(void)
{
static int i = 5;
static int t = GetTickCount();
...
}

Is the variable created/initialized only after the function is called for the first time? Or will it be created/initialized at the beginning of the program (although I don't know how this can be done in the second case). Is this behaviour specified in C/C++?

Thanks.
closed account (zb0S216C)
The variable is created first, followed by the execution of the method. When the method returns, the returning value is used to initialize the object.
So if the function f() is called 10s after the program has started, I can be sure that the variable t will be initiallized to 10 instead of something else? Thanks.
Last edited on
closed account (zb0S216C)
Champion wrote:
So if the function f() is called 10s after the program
f( ) cannot be called once the program has been terminated. Unless you you meant something else.

I can be sure that the variable t will be initiallized to 10 instead of something else?
static objects in functions will keep the value from one function call to another, for example:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <iostream>

using std::endl;
using std::cout;
using std::cin;

int Static_function( void )
{
    static int i_Counter( 0 );
    return( i_Counter++ );
}

int main( )
{
    for( int i_Loop( 0 ); i_Loop < 3; i_Loop++ )
        cout << Static_function( ) << endl;

    cin.get( );
    return 0;
}

If you run this code, the output should be:
0
1
2
static objects in general will last for the lifetime of the entire program[1].

References:
[1]http://en.wikipedia.org/wiki/Static_variable
Last edited on
Topic archived. No new replies allowed.