ARM Technical Support Knowledge Articles

COMPILER INITIALIZES GLOBAL VARIABLES TO 0

Applies to: General Topics

Answer


Information in this article applies to:


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.

Article last edited on: 2005-07-18 09:50:02

Rate this article

[Bad]
|
|
[Good]
Disagree? Move your mouse over the bar and click

Did you find this article helpful? Yes No

How can we improve this article?

Link to this article
Copyright © 2011 ARM Limited. All rights reserved. External (Open), Non-Confidential