By buzali


2009-09-12 03:45:48 8 Comments

When declaring an array in C like this:

int array[10];

What is the initial value of the integers?? I'm getting different results with different compilers and I want to know if it has something to do with the compiler, or the OS.

8 comments

@sergej 2019-02-26 15:35:28

The relevant sections from the C standard (emphasis mine):

5.1.2 Execution environments

All objects with static storage duration shall be initialized (set to their initial values) before program startup.

6.2.4 Storage durations of objects

An object whose identifier is declared with external or internal linkage, or with the storage-class specifier static has static storage duration.

6.2.5 Types

Array and structure types are collectively called aggregate types.

6.7.8 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, then:

  • if it has pointer type, it is initialized to a null pointer;
  • if it has arithmetic type, it is initialized to (positive or unsigned) zero;
  • if it is an aggregate, every member is initialized (recursively) according to these rules;
  • if it is a union, the first named member is initialized (recursively) according to these rules.

@DigitalRoss 2009-09-12 04:35:21

Why are function locals (auto storage class) not initialized when everything else is?

C is close to the hardware; that's its greatest strength and its biggest danger. The reason auto storage class objects have random initial values is because they are allocated on the stack, and a design decision was made not to automatically clear these (partly because they would need to be cleared on every function call).

On the other hand, the non-auto objects only have to be cleared once. Plus, the OS has to clear allocated pages for security reasons anyway. So the design decision here was to specify zero initialization. Why isn't security an issue with the stack, too? Actually it is cleared, at first. The junk you see is from earlier instances of your own program's call frames and the library code they called.

The end result is fast, memory-efficient code. All the advantages of assembly with none of the pain. Before dmr invented C, "HLL"s like Basic and entire OS kernels were really, literally, implemented as giant assembler programs. (With certain exceptions at places like IBM.)

@Zan Lynx 2009-09-12 03:54:53

A C variable declaration just tells the compiler to set aside and name an area of memory for you. For automatic variables, also known as stack variables, the values in that memory are not changed from what they were before. Global and static variables are set to zero when the program starts.

Some compilers in unoptimized debug mode set automatic variables to zero. However, it has become common in newer compilers to set the values to a known bad value so that the programmer does not unknowingly write code that depends on a zero being set.

In order to ask the compiler to set an array to zero for you, you can write it as:

int array[10] = {0};

Better yet is to set the array with the values it should have. That is more efficient and avoids writing into the array twice.

@buzali 2009-09-12 04:24:22

Do you know how can tell the compiler to set the values to zero?? I'm using GCC... is there any debug parameter that does this?

@Eclipse 2009-09-12 04:43:04

Don't depend on the compiler to initialize the array use an explicit initializer like Zan suggests. Even if the current gcc zeros arrays in some debug mode, the next one may decide to fill them with a totally different value, leaving you with a very hard to locate bug 5 years down the road. Just type the extra 5 characters and use int array[10] = {0};

@qrdl 2009-09-12 06:10:12

Obviously incorrect. Variables from data segment are always zeroed.

@user3063349 2017-09-12 13:46:07

far not always zeroed

@mav_2k 2009-09-13 04:41:21

In most latest compilers(eg. gcc/vc++), partially initialized local array/structure members are default initialized to zero(int), NULL(char/char string), 0.000000(float/double).

Apart from local array/structure data as above, static(global/local) and global space members are also maintain the same property.

int a[5] = {0,1,2};
printf("%d %d %d\n",*a, *(a+2), *(a+4));

struct s1
{
int i1;
int i2;
int i3;
char c;
char str[5];
};

struct s1 s11 = {1};
    printf("%d %d %d %c %s\n",s11.i1,s11.i2, s11.i3, s11.c, s11.str);
    if(!s11.c)
        printf("s11.c is null\n");
    if(!*(s11.str))
        printf("s11.str is null\n");

In gcc/vc++, output should be:

0 2 0 1 0 0 0.000000 s11.c is null s11.str is null

@AraK 2009-09-12 03:48:41

If the array is declared in a function, then the value is undefined. int x[10]; in a function means: take the ownership of 10-int-size area of memroy without doing any initialization. If the array is declared as a global one or as static in a function, then all elements are initialized to zero if they aren't initialized already.

@JasonWoof 2009-09-12 03:52:51

correct. Unless it's global, it'll contain whatever random junk was in that chuck of memory before. Has nothing to do with the compiler. If you want something in particular in there, put it there.

@buzali 2009-09-12 03:54:22

ok, I'm using XCode and for some reason all the elements in the array are initialized to zero and it's inside a function. any ideas why? is it because of the compiler, the IDE, or the OS??

@AraK 2009-09-12 04:08:30

@buzali The only case I can think of is when array is static. Otherwise I have no idea really.

@Drakonite 2009-09-12 04:16:53

@buzali Some compilers/toolchains will always zero variables and allocated memory, most often when you are building in "debug" mode (no optimizations enabled). This is typically intended to create a deterministic debugging environment for when you are prototyping code and forget to initialize a variable. The other possibility is the memory the array is using just happens to contain zeros.

@buzali 2009-09-12 04:32:20

@Drakonite, that's exactly what I want. Do you know how to set GCC into debug mode so that i'll zero all items in the array?

@qrdl 2009-09-12 06:07:59

Incorrect. Variable scope doesn't matter - storage class does.

@Steve Jessop 2009-09-12 13:08:22

@buzali: no, it isn't what you want. If you want to initialize the array to zeros, then write int array[10] = {0};. Getting the compiler to do it automatically just means you're writing code that only works in debug mode, and breaks when you release it, or someone else compiles it with different options.

@Steve Melnikoff 2009-09-12 16:04:31

@AraK: it may also be worth adding to your answer that a static variable defined inside a function will also be initialised to zeroes.

@AraK 2009-09-12 16:12:51

@Steve Added to the answer. Thanks :)

@Antti Haapala 2017-08-18 07:16:00

Such values are not called undefined but indeterminate in the C standard. (Except for the one place that says "undefined value" in C11...)

@ygoe 2020-01-27 21:34:04

Am I correct that this initialisation with zeros also applies to an array of structs?

@qrdl 2009-09-12 06:05:53

As set by the standard, all global and function static variables automatically initialised to 0. Automatic variables are not initialised.

int a[10];  // global - all elements are initialised to 0

void foo(void) {
    int b[10];    // automatic storage - contain junk
    static int c[10]; // static - initialised to 0
}

However it is a good practice to always manually initialise function variable, regardless of its storage class. To set all array elements to 0 you just need to assign first array item to 0 - omitted elements will set to 0 automatically:

int b[10] = {0};

@John Bode 2009-09-12 14:23:41

To be pedantic, file scope variables (globals) have storage class static, which is why they're initialized to 0.

@qrdl 2009-09-12 15:34:48

@John Yes, but because static on file level has a different meaning, I just called it 'global', be it file global or program global

@Martin James 2014-07-28 19:33:55

I can't see why it's good practice to waste cycles on initializing a large buffer that, in the next line, you are going to load up with data from a file/network.

@adatapost 2009-09-12 04:03:51

Text from http://www.cplusplus.com/doc/tutorial/arrays/

SUMMARY:

Initializing arrays. When declaring a regular array of local scope (within a function, for example), if we do not specify otherwise, its elements will not be initialized to any value by default, so their content will be undetermined until we store some value in them. The elements of global and static arrays, on the other hand, are automatically initialized with their default values, which for all fundamental types this means they are filled with zeros.

In both cases, local and global, when we declare an array, we have the possibility to assign initial values to each one of its elements by enclosing the values in braces { }. For example:

int billy [5] = { 16, 2, 77, 40, 12071 };

@MSN 2009-09-12 03:58:35

According to the C standard, 6.7.8 (note 10):

If an object that has automatic storage duration is not initialized explicitly, its value is indeterminate.

So it depends on the compiler. With MSVC, debug builds will initialize automatic variables with 0xcc, whereas non-debug builds will not initialize those variables at all.

Related Questions

Sponsored Content

97 Answered Questions

[SOLVED] How can I remove a specific item from an array?

  • 2011-04-23 22:17:18
  • Walker
  • 6974499 View
  • 8528 Score
  • 97 Answer
  • Tags:   javascript arrays

39 Answered Questions

[SOLVED] Loop through an array in JavaScript

37 Answered Questions

[SOLVED] Create ArrayList from array

41 Answered Questions

[SOLVED] For-each over an array in JavaScript

28 Answered Questions

[SOLVED] How do I declare and initialize an array in Java?

  • 2009-07-29 14:22:27
  • bestattendance
  • 4568648 View
  • 2092 Score
  • 28 Answer
  • Tags:   java arrays

47 Answered Questions

[SOLVED] Sort array of objects by string property value

53 Answered Questions

31 Answered Questions

[SOLVED] What's the simplest way to print a Java array?

  • 2009-01-03 20:39:39
  • Alex Spurling
  • 2328356 View
  • 1975 Score
  • 31 Answer
  • Tags:   java arrays printing

22 Answered Questions

[SOLVED] How to initialize all members of an array to the same value?

10 Answered Questions

[SOLVED] Improve INSERT-per-second performance of SQLite

Sponsored Content