4
string array[] = "";

How am I able to assign a const char* to an array? Is that the same as:

string array[] = {""};

?? That would make sense to me. However, this still doesn't work

int array[] = 5;

So what is the difference between them that it doesn't work for int arrays?

sashoalm
  • 75,001
  • 122
  • 434
  • 781
Me myself and I
  • 3,990
  • 1
  • 23
  • 47
  • That shouldn't compile. There are some special rules to allow you to initialise a character array from a string literal; but not an array of anything else. – Mike Seymour Jan 31 '14 at 13:57
  • What is the type of `string`? If it's `std::string` (as it should be), then your first line shouldn't compile. If it's `typedef char string;`, however, this would be the classical initialization of a `char[]`. – James Kanze Jan 31 '14 at 14:01
  • And of course, the type of `""` isn't `char const*`, but `char const [1]`. – James Kanze Jan 31 '14 at 14:04
  • @JamesKanze It is a `std::string`. – Me myself and I Jan 31 '14 at 14:24

2 Answers2

5

This is incorrect code; it is a bug in your compiler (possibly gcc/g++?) to accept it.

clang gives the following error (link):

a.cpp:5:17: error: array initializer must be an initializer list
    std::string array[] = "";
                ^
1 error generated.

Visual C++ agrees (link):

testvc.cpp(2) : error C3074: an array can only be initialized with an initializer-list

The relevant clause in the standard is 8.5p17:

[...]
— If the destination type is an array of characters, an array of char16_t, an array of char32_t, or an array of wchar_t, and the initializer is a string literal, see 8.5.2.
[...]
— Otherwise, if the destination type is an array, the program is ill-formed.
[...]

Submitted to gcc as a bug: http://gcc.gnu.org/bugzilla/show_bug.cgi?id=60009

ecatmur
  • 152,476
  • 27
  • 293
  • 366
0

Actually, that functionality is a carryover from the initialization of empty char arrays.(std::string acts very similar to char.)

char buf[10] = ""; is equivalent to char buf[10] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0};, but char buf[10] = "a"; is equivalent to char buf[10] = {'a', 0, 0, 0, 0, 0, 0, 0, 0, 0};. Why? Since char is an arithmetic value, it is auto-initialized to zero.

Your compiler sees "" as a char value (const char*, technically) and simply casts it to an std::string. While this is not exactly up to standard, it works on most compilers.

Proxy
  • 1,824
  • 1
  • 16
  • 27