Keil Logo

GENERAL: COMPILER INITIALIZES GLOBAL VARIABLES TO 0


Information in this article applies to:

  • C166 Version 3.12
  • C166 Version 4.03
  • C251 Version 2.14
  • C51 Version 5.50
  • C51 Version 6.00 Beta
  • C51 Version 6.00

SYMPTOMS

I think I've found a problem with the C compiler. It sets my uninitialized global variables to 0. For example:

int junk;
static int static_junk;

void main (void)
{
}

In this example, junk should be left uninitialized while static_junk should be initialized to 0. Why isn't the Keil compiler ANSI compliant in this respect?

CAUSE

The Keil compiler is ANSI compliant in the implementation of initializing variables. According to the ANSI specification...

6.1.2.4 Storage Duration of Objects

An object has a storage duration that determines its lifetime. There are two storage durations: static and automatic. An object whose identifier is declared with external or internal linkage, or with the storage-class specifier static has static storage duration. For such an object, storage is reserved and its stored value is initialized only once, prior to program startup...

An object whose identifier is declared with no linkage and without the storage-class specifier static has automatic storage duration...

6.5.7 Initialization

...If an object that has automatic storage duration is not initialized explicitly, its value is indeterminate. If an object that has static storage duration is not initialized explicitly, it is initialized implicitly as if every member that has arithmetic type were assigned 0 and every member that has pointer type were assigned a null pointer constant.

Do not confuse the static storage duration with the static keyword used to specify the storage-class. These are distinct. The spec clearly states in the above that all uninitialized global variables (those declared outside of a function block) will be assigned the value 0.

Last Reviewed: Monday, July 18, 2005


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.