Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

the array Initialize in C++ [duplicate]

Tags:

c++

c++11

#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 are all 0. but if i just wrtie int arr[10], the elements in arr are random. So i am confused about int arr[10] = {}, i just declare a array int arr[10], but i don't give it any value, just a {}.

like image 903
BlackMamba Avatar asked Mar 10 '16 06:03

BlackMamba


1 Answers

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

That is just how the syntax of the language works. In your case the array will be zero initialized.

but if i just wrtie int arr[10], the elements in arr are random.

In your case array elements are not initialized. You should not read values of variables which are not initialized; otherwise you will trigger undefined behavior.

like image 178
Giorgi Moniava Avatar answered Oct 27 '22 01:10

Giorgi Moniava