"static"?

This is a discussion on "static"? within the C Programming forums, part of the General Programming Boards category; Hi I came across this piece of code but I don't know what "static" does!? I suppose its something similar ...

  1. #1
    Registered User
    Join Date
    May 2004
    Posts
    7

    "static"?

    Hi I came across this piece of code but I don't know what "static" does!?
    I suppose its something similar to DEFINE, but what's the difference?

    Code:
    typedef float WorldType;
    
    static WorldType 
    	  X = 45.0, 	
    	  Y = 5.17;
    thanks in advance,
    Khelmo

  2. #2
    ATH0 quzah's Avatar
    Join Date
    Oct 2001
    Posts
    14,826
    No. Nothing like #define. Static when used with local variables means they will persist over function calls, unlike automatic variables:
    Code:
    void showstatic( void )
    {
        static int x;
        printf("x is %d, and this function has been called %d times now.\n", x, x+1 );
        x++;
    }
    
    void showautomatic( void )
    {
        int x;
        printf("x is %d and this function has been called %d times.\n", x, x+1 );
        x++;
    }
    If you run both of these functions, in something like:
    Code:
    int x;
    for( x = 0; x < 3; x++ )
    {
        showstatic( );
        showautomatic( );
    }
    Then the first function will show you the value of x, and it will increment x every time you call the function. The second function will not work in the same way. This shows you another nifty thing about static when compared to automatic variables:

    Static variables are automatically initialized to zero before they're ever used. This is why we can get away without setting it to anything in the function showstatic, and why it doesn't work right when we do the same thing in showautomatic. Automatic variables are not initialized. (Any variable not declared static is considered automatic for out purposes.)

    static when used on a globally that item to the scope of the file.
    Code:
    static hiddenfunction( void )
    {
        printf("This function can only be called from the file it's declared in.\n");
    }

    Quzah.
    Hope is the first step on the road to disappointment.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Should "static" variable always be local to a file?
    By meili100 in forum C++ Programming
    Replies: 3
    Last Post: 06-22-2008, 11:51 PM
  2. Moving A Picture..slight prob
    By Xterria in forum Windows Programming
    Replies: 4
    Last Post: 02-27-2002, 08:05 PM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21