0

I encountered this problem while writing a program.

#include<iostream>
using namespace std;
string a[10];
int b[10];
int main(){
    string a1[10];
    int b1[10];
    for(auto i:a){cout<<i<<" ";}
    cout<<endl;
    for(auto i:b){cout<<i<<" ";}
    cout<<endl;
    for(auto i:a1){cout<<i<<" ";}
    cout<<endl;
    for(auto i:b1){cout<<i<<" ";}
    cout<<endl;
    return 0;
}

According to the output, elements of a and a1 are both empty strings, while b has all zero but b1 seems to have some random nubmers. I don't know what caused the difference between string and int, and between a and a1(Maybe compiler initialized variables in different scopes in different ways? So what's the purpose of this design?). Can anyone help?

sirius27
  • 101
  • 4
  • 2
    Possible duplicate of [Why are global and static variables initialized to their default values?](https://stackoverflow.com/questions/2091499/why-are-global-and-static-variables-initialized-to-their-default-values) – Rakete1111 Jun 10 '17 at 16:55
  • 2
    an array of `std::string` s will be default constructed, and all the elements of the global array `b` will be initialized to 0. local scope primitives aren't initialized by default, the reason is that not non-static and non-global initialization incur a runtime cost. – George Jun 10 '17 at 16:58
  • Possible duplicate of [value of allocated array not initialized](https://stackoverflow.com/questions/5878957/value-of-allocated-array-not-initialized) – alejandrogiron Jun 10 '17 at 17:00
  • Possible duplicate of [What happens to a declared, uninitialized variable in C? Does it have a value?](https://stackoverflow.com/questions/1597405/what-happens-to-a-declared-uninitialized-variable-in-c-does-it-have-a-value) – Weak to Enuma Elish Jun 10 '17 at 17:04
  • @Rakete1111 thanks. It seems to have answerd the second question...but why is non-global string also empty-initialized? – sirius27 Jun 10 '17 at 17:05
  • @sirius27 That's because `std::string` is a class which has a default constructor that initializes it to nothing. `int` is a POD, and as such, it doesn't have a default constructor. – Rakete1111 Jun 10 '17 at 17:06
  • @George Thanks! it's quite clear – sirius27 Jun 10 '17 at 17:06
  • @Rakete1111 thanks – sirius27 Jun 10 '17 at 17:07

0 Answers0