View previous topic :: View next topic |
Author |
Message |
valemike Guest
|
"static" keyword in a function... |
Posted: Mon Aug 16, 2004 2:26 pm |
|
|
I understood that the "static" keyword, when used in a function, will retain its value when you exit the function.
Code: |
/* Look at the keys */
int16 scan_keys(void)
{
int16 snapshot;
static int scankey_state = SCANKEY_STATE_IDLE;
static int pending_key_number = 0xFF;
static int16 pending_scanmask = 0;
[snip]
...
}
|
This function is called in a while(1) loop in main().
For some reason, scankey_state always gets reset at the value SCANKEY_STATE_IDLE everytime i call the function. However, pending_scanmask retains its value as I expect.
The only way to get around this is if I delete the local static declaration of scankey_state, and instead declare it globally near the top of the .c file.
Has anyone ever experienced this type of behaviour - i.e. a locally declared static variable loses its value upon further invocations of that function? (compiler version is PCWH 3.187) |
|
|
Mark
Joined: 07 Sep 2003 Posts: 2838 Location: Atlanta, GA
|
|
Posted: Mon Aug 16, 2004 2:44 pm |
|
|
Post the #asm instructions (LST file) and take a look at what the compiler is doing.
Also, make sure that the WDT or anything else is not resetting the processor as that would reset the value. |
|
|
Guest
|
Re: "static" keyword in a function... |
Posted: Mon Aug 16, 2004 2:47 pm |
|
|
ORIGINAL CODE:
Code: |
/* Look at the keys */
int16 scan_keys(void)
{
int16 snapshot;
[b]static int scankey_state = SCANKEY_STATE_IDLE;[/b]
static int pending_key_number = 0xFF;
static int16 pending_scanmask = 0;
[snip]
...
}
|
After re-arranging the order of the declarations:
/* Look at the keys */
int16 scan_keys(void)
{
int16 snapshot;
// static int scankey_state = SCANKEY_STATE_IDLE;
static int pending_key_number = 0xFF;
static int16 pending_scanmask = 0;
static int scankey_state = SCANKEY_STATE_IDLE;
[snip]
...
}
By rearranging the order in which i declare them, then scankey_state retains its value; however i haven't checked what happens to pending_key_number.
What is happening here |
|
|
Mark
Joined: 07 Sep 2003 Posts: 2838 Location: Atlanta, GA
|
|
Posted: Mon Aug 16, 2004 2:58 pm |
|
|
The lst file will tell you! |
|
|
valemike Guest
|
|
Posted: Mon Aug 16, 2004 3:40 pm |
|
|
Yup, the .lst file doesn't lie.
In this case i didn't look at the .lst file. I commented out a certain function call in that function, and unsurprisingly, that the static variables dont get overwritten.
That function call I commented out does some char typecasting on a local int16. I know I didn't go out-of-bounds as far as the K&R book's rules. Nor did I want to spend the rest of my day figuring out what really happened. So i figured i'd rewrite the function by passing in a pointer to an array instead of working on a local int16.
Who knows what happened. But the re-implementation now works. |
|
|
|