Array initialization in C ++

#include <iostream> using namespace std; int main() { int arr[10] = {}; for(auto element : arr) { cout<<element<<" "; } cout<<endl; } 

if I write int arr[10] = {} , the elements in arr all 0 . but if I just wrtie int arr[10] , the elements in arr are random. So I'm confused about int arr[10] = {} , I just declare an array int arr[10] , but I don't give it any value, just {} .

+6
source share
3 answers

if I write int arr [10] = {}, the elements from arr are all 0.

This is how the language syntax works. In your case, the array will be initialized to zero.

but if I just wr intie [10], the elements from arr are random.

In your case, the elements of the array are not initialized. You should not read the values โ€‹โ€‹of variables that are not initialized; otherwise, you will trigger undefined behavior.

+5
source

according to cpp help site ( http://en.cppreference.com/w/c/language/array_initialization ) to initialize all array elements to zero:

int a [3] = {}; // invalid C, but a valid C ++ way to nullify an array with block scope

+2
source

int arr[10]; does not initialize anything, it allocates memory blocks of size int , and you get what ever was in that memory.

int arr[10] = {}; initializes all int blocks to zero / 0

0
source

All Articles