This is the mail archive of the gcc-help@gcc.gnu.org mailing list for the GCC project.


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]
Other format: [Raw text]

RE: Initialization of arrays (newbie)


Steve Dondley wrote:

> I've read on the net that a declaration such as
> int a[100];
> results in all the elements of the array getting initialized to 0.

Only if it's at global scope. If it's a variable declared in a function,
it doesn't.

   6.7.8.10:

        If an object that has automatic storage duration is not
        initialized explicity, its 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 integer 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.

> However, this doesn't appear to be the case with gcc.

It does correctly initialize global arrays to zero, e.g.

    #include <stdio.h>
    int a[100];
    int main(void)
    {
        int i = 0;
        for(;i<100;i++)
            printf("%4d",a[i]);
        printf("\n");
        return 0;
    }

outputs all zeros.

> I have to use a for loop and manually set each element to zero.
> There must be a better way. What is it?

No, that's probably about it. You could use a memset, e.g.

    memset(a, 0, sizeof(a));

or thereabouts, but I guess it's up to you whether you like that as a
point of style. Probably little difference in the code (assuming memset
is inlined as a built-in - otherwise memset probably loses).

Hope that helps,
Rup.


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]