Thread: question on the use of 'static'

  1. #1
    Registered User
    Join Date
    Mar 2020
    Posts
    75

    question on the use of 'static'

    I have a file file.c where I define (at the beginning of the function within file.c)
    Code:
        static char sensor = EMPTY_MEMORY;
    Within this file sensor gets assigned a value other than above. My question is when I leave this file and go back to main.c, then re-enter this file will sensor retain the last value or will it get re-initialized to EMPTY_MEMORY again?

    Thanks

  2. #2
    Registered User rstanley's Avatar
    Join Date
    Jun 2014
    Location
    New York, NY
    Posts
    798
    A static variable holds the value the last time the function was called. The variable was only initialized once the first time the function is called. Static local varriables are stored in the Global Data segment, not on the stack.

    Review this example:
    Code:
    #include <stdio.h>
    
    void test(void);
    
    int main(void)
    {
       // First call
       test();
    
       // Second call after increment
       test();
    
       // Third test
       test();
    
       return 0;
    }
    
    
    void test(void)
    {
       static int val = 10;
    
       printf("Current value of val: %d\n", val);
    
       val++;
    }
    Output:
    Code:
    Current value of val: 10
    Current value of val: 11
    Current value of val: 12

  3. #3
    Registered User
    Join Date
    Mar 2020
    Posts
    75
    Thank you! That answers my question.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. A question about static.
    By User Name: in forum C Programming
    Replies: 29
    Last Post: 06-17-2010, 08:17 PM
  2. Static Initilization question
    By tezcatlipooca in forum C++ Programming
    Replies: 1
    Last Post: 12-29-2006, 07:09 PM
  3. Static lib question
    By X PaYnE X in forum Windows Programming
    Replies: 2
    Last Post: 08-08-2006, 11:55 AM
  4. static bool question...
    By jerrykelleyjr in forum C++ Programming
    Replies: 2
    Last Post: 02-17-2005, 09:39 AM
  5. question about static members
    By Shadow12345 in forum C++ Programming
    Replies: 3
    Last Post: 01-07-2003, 10:21 AM

Tags for this Thread