Thread: I wonder why

  1. #1
    Registered User
    Join Date
    Jun 2006
    Posts
    30

    I wonder why

    Can someone explain me one thing, why do you put static variables in the main function of the program. For example, in Petzold's "Programming Windows", he has
    Code:
    WinMain(...) {
         static TCHAR szAppName[] = TEXT("HelloWin");
         HWND hWnd;
         MSG msg;
         WNDCLASS wndClass;
    ...
    }
    Why does he make szAppName static if WinMain is only called once? Another question is - why only szAppName is declared static but not the rest of the variables? I just dont see the reason to make variables static in main function.

  2. #2
    Registered User Tonto's Avatar
    Join Date
    Jun 2005
    Location
    New York
    Posts
    1,465
    I believe that without the static keyword, it would generate code to copy the string "HelloWin" from a read-only data to mutable data on the stack. As it is, the compiler will allocate memory for the string and initialize it with the text "HelloWin", instead of code doing such a thing at run time.

  3. #3
    Registered User
    Join Date
    Jun 2006
    Posts
    30
    I don't quite follow your explanation. Isn't static has only one meaning, that is, making a variable exist after the function is terminated?

  4. #4
    Registered User Tonto's Avatar
    Join Date
    Jun 2005
    Location
    New York
    Posts
    1,465

  5. #5
    Registered User
    Join Date
    Jun 2006
    Posts
    30
    Thank you for the link. But why the rest of the variables are not declared as static?

  6. #6
    Registered User Tonto's Avatar
    Join Date
    Jun 2005
    Location
    New York
    Posts
    1,465
    The reason I gave was certainly frivolous; the instructions needed to copy the string are extremely fast, but I can not think of any other reason. The other local variables do not require any particular initialization like the string does, and are space for them is allocated with a single instruction.

  7. #7
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,659
    > Why does he make szAppName static if WinMain is only called once?
    Presumably that variable (actually a pointer, since it is an array) gets passed to some other function.
    That function keeps the pointer (rather than making a copy), and refers to it after winMain() has exited.
    So in order to stop the variable going out of scope when the function exits, it is made static.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

Popular pages Recent additions subscribe to a feed