Keil Logo

C51: Local Variables Preserve Values Between Function Calls


Information in this article applies to:

  • C51 version 5.50 and later

QUESTION

If I declare a local variable called 'foo' in the following way, is it supposed to preserve its value between function calls? We have noticed that for certain projects the value is preserved, but in other projects it is corrupted.

void bar(void)
{
  unsigned char foo;

  P1 = foo;
}

ANSWER

The variable foo is located in the default memory area for the selected memory model. In addition, the default memory area is also overlaid with variables that are mutually exclusive in use. This data overlaying means that local variables may retain their value depending on memory usage.

For example, suppose you are using the code above in the Small memory model. The variable foo will be located in data memory. Suppose also that there is another function with a local variable called baz. This function is never executing when bar() is and vice versa. The local variables foo and baz may be overlaid so they use the same memory locations. The result is that neither variable retains its value between function calls.

Only the default memory area for the selected memory model is overlaid. For example, if you are using the Small memory model and you declare a local variable to be in pdata or xdata, the variable retains its value between function calls. However, this may change in future versions of the Compiler and must not be relied upon.

The following is from the ANSI C Standard (section 6.1.2.4 Storage Duration of Objects):

"storage for the object is no longer guaranteed to be reserved when execution of the block ends in any way"

MORE INFORMATION

  • Refer to Section 6.1.2.4 Storage Duration of Objects in the ANSI C Standard (ANSI/ISO 9899-1990).

SEE ALSO


Last Reviewed: Thursday, February 25, 2021


Did this article provide the answer you needed?
 
Yes
No
Not Sure
 
  Arm logo
Important information

This site uses cookies to store information on your computer. By continuing to use our site, you consent to our cookies.

Change Settings

Privacy Policy Update

Arm’s Privacy Policy has been updated. By continuing to use our site, you consent to Arm’s Privacy Policy. Please review our Privacy Policy to learn more about our collection, use and transfers
of your data.