LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   C - Does a static declaration reinitate the value when recalled? (https://www.linuxquestions.org/questions/programming-9/c-does-a-static-declaration-reinitate-the-value-when-recalled-819146/)

golmschenk 07-10-2010 07:47 PM

C - Does a static declaration reinitate the value when recalled?
 
I'm guesing not, but would a code of something like:
Code:

static int foo = 0;
when recalled reset the value to zero? Because although it's already been initialized and that doesn't happen again, does the = 0 part still effect it? Like I said, it doesn't make sense to me that it would but I decided I'd ask. Thanks!

easuter 07-10-2010 09:30 PM

When in doubt about small things like this in C, I like to write a quick program to test the problem (it generally saves tons more time than posting on a forum):

Code:

#include <stdio.h>

void test_static(int bar)
{
        static int foo = 0;
        printf("foo is: %d\n", foo);
        foo = bar;
        printf("foo is: %d\n", foo);
}

int main(void)
{
        test_static(2);
        test_static(100);

        return 0;
}

The output from that is:

Code:

foo is: 0
foo is: 2
foo is: 2
foo is: 100

I guess that answers your question :)
BTW, setting a static variable to zero is unnecessary, since K&R's book indicates that static variables get automatically initialized to zero.

golmschenk 07-10-2010 11:32 PM

Awesome. Perfect thanks. Yeah, I had considered writing a small program to test it, but I was working on another one and decided that someone would know on here so I could be lazy and not do it myself. Thanks a ton! Very descriptive answer.


All times are GMT -5. The time now is 04:50 AM.