How Does Array[100] = {0} Set the Entire Array to 0

how does array[100] = {0} set the entire array to 0?

It's not magic.

The behavior of this code in C is described in section 6.7.8.21 of the C specification (online draft of C spec): for the elements that don't have a specified value, the compiler initializes pointers to NULL and arithmetic types to zero (and recursively applies this to aggregates).

The behavior of this code in C++ is described in section 8.5.1.7 of the C++ specification (online draft of C++ spec): the compiler aggregate-initializes the elements that don't have a specified value.

Also, note that in C++ (but not C), you can use an empty initializer list, causing the compiler to aggregate-initialize all of the elements of the array:

char array[100] = {};

As for what sort of code the compiler might generate when you do this, take a look at this question: Strange assembly from array 0-initialization

How to initialize array to 0 in C?

Global variables and static variables are automatically initialized to zero. If you have simply

char ZEROARRAY[1024];

at global scope it will be all zeros at runtime. But actually there is a shorthand syntax if you had a local array. If an array is partially initialized, elements that are not initialized receive the value 0 of the appropriate type. You could write:

char ZEROARRAY[1024] = {0};

The compiler would fill the unwritten entries with zeros. Alternatively you could use memset to initialize the array at program startup:

memset(ZEROARRAY, 0, 1024);

That would be useful if you had changed it and wanted to reset it back to all zeros.

C/C++: How does int array[10]={0} work?

Depends on the scope of your variable.

  1. Global scope - array will be placed in the .bss segment and zeroed before call to the main function. Is it faster? It is definitely different as zeroing takes place before the main start
  2. Local scope - the {0} initialisation will be IMO faster as those internal routines are well optimised for the particular hardware. I have tested with gcc & VS and it is quicker - but of course there is no guarantee that your compiler will do it the same way. https://godbolt.org/g/JdTPHJ

C/C++: How does int array[10]={0} work?

Depends on the scope of your variable.

  1. Global scope - array will be placed in the .bss segment and zeroed before call to the main function. Is it faster? It is definitely different as zeroing takes place before the main start
  2. Local scope - the {0} initialisation will be IMO faster as those internal routines are well optimised for the particular hardware. I have tested with gcc & VS and it is quicker - but of course there is no guarantee that your compiler will do it the same way. https://godbolt.org/g/JdTPHJ

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

Unless that value is 0 (in which case you can omit some part of the initializer
and the corresponding elements will be initialized to 0), there's no easy way.

Don't overlook the obvious solution, though:

int myArray[10] = { 5, 5, 5, 5, 5, 5, 5, 5, 5, 5 };

Elements with missing values will be initialized to 0:

int myArray[10] = { 1, 2 }; // initialize to 1,2,0,0,0...

So this will initialize all elements to 0:

int myArray[10] = { 0 }; // all elements 0

In C++, an empty initialization list will also initialize every element to 0.
This is not allowed with C until C23:

int myArray[10] = {}; // all elements 0 in C++ and C23

Remember that objects with static storage duration will initialize to 0 if no
initializer is specified:

static int myArray[10]; // all elements 0

And that "0" doesn't necessarily mean "all-bits-zero", so using the above is
better and more portable than memset(). (Floating point values will be
initialized to +0, pointers to null value, etc.)

How all the elements of array initialize to zero and first element to 1 in c

The array elements are initialized based on the initialization rule for aggregate type with initialization lists, as specified in C standard.

It mentions, if there are less number of initializers supplied in the brace-enclosed list than that of the number of element in the aggregate type, the remaining elements in the aggregate type will be initialized with the value as if they have static storage duration, i.e., a value of 0.

To quote C11, chapter §6.7.9, Initialization (emphasis mine)

If there are fewer initializers in a brace-enclosed list than there are elements or members of an aggregate, or fewer characters in a string literal used to initialize an array of known size than there are elements in the array, the remainder of the aggregate shall be initialized implicitly the same as objects that have static storage duration.

and regarding the initialization of variables having static storage duration,

[..] If an object that has static or thread storage duration is not initialized
explicitly, then:

  • [...]
  • if it has arithmetic type, it is initialized to (positive or unsigned) zero;
  • [...]

So, very rightly, in your case

  int arr[10]={1};

arr[0] is having a value 1, arr[1] to arr[9] all are set to 0.

Set an array to zero with c++11

You might use std::fill:

std::fill(std::begin(array), std::end(array), 0);

Any shortcut to initialize all array elements to zero?

A default value of 0 for arrays of integral types is guaranteed by the language spec:

Each class variable, instance variable, or array component is initialized with a default value when it is created (§15.9, §15.10) [...] For type int, the default value is zero, that is, 0.  

If you want to initialize an one-dimensional array to a different value, you can use java.util.Arrays.fill() (which will of course use a loop internally).

Reset C int array to zero : the fastest way?

memset (from <string.h>) is probably the fastest standard way, since it's usually a routine written directly in assembly and optimized by hand.

memset(myarray, 0, sizeof(myarray)); // for automatically-allocated arrays
memset(myarray, 0, N*sizeof(*myarray)); // for heap-allocated arrays, where N is the number of elements

By the way, in C++ the idiomatic way would be to use std::fill (from <algorithm>):

std::fill(myarray, myarray+N, 0);

which may be optimized automatically into a memset; I'm quite sure that it will work as fast as memset for ints, while it may perform slightly worse for smaller types if the optimizer isn't smart enough. Still, when in doubt, profile.



Related Topics



Leave a reply



Submit