Page 1 of 1
What Does This Code Do?
Posted: Mon Aug 26, 2013 3:02 am
by X Abstract X
I came across this code that compiles and runs (XCode, iOS) but it definitely isn't initializing the contents of the array. I'm pretty certain it's got to be doing something nasty. Can anyone explain this?
Code: Select all
std::string* myStrings = new std::string[4] { "Apples", "Oranges", "Bananas", "Coconuts" };
Re: What Does This Code Do?
Posted: Mon Aug 26, 2013 8:29 am
by Nokurn
I am not sure I see what you mean. This code produces an error in C++98/03, since it uses an initializer list, but compiles and executes correctly in C++11:
Code: Select all
Jeremiah@mercury:~/Desktop% cat myStrings.cpp
#include <iostream>
#include <string>
int main()
{
std::string* myStrings = new std::string[4] { "Apples", "Oranges", "Bananas", "Coconuts" };
for (int i = 0; i < 4; ++i)
std::cout << i << ": " << myStrings[i] << std::endl;
return 0;
}
Jeremiah@mercury:~/Desktop% c++ myStrings.cpp -o myStrings
myStrings.cpp:5:48: error: expected ';' at end of declaration
std::string* myStrings = new std::string[4] { "Apples", "Oranges", "Bananas", "Coconuts" };
^
;
1 error generated.
Jeremiah@mercury:~/Desktop% c++ -std=c++11 -stdlib=libc++ myStrings.cpp -o myStrings
Jeremiah@mercury:~/Desktop% ./myStrings
0: Apples
1: Oranges
2: Bananas
3: Coconuts
This is with Clang 3.3 on Mac OS X, but the behavior is the same on GCC 4.8.1 on Arch Linux.
If your misunderstanding comes from the use of {} to initialize a dynamically allocated array by assignment: This is a new feature in C++11 known as initializer lists, which Wikipedia has a good
overview of. They're one of my favorite parts of C++11.
Re: What Does This Code Do?
Posted: Mon Aug 26, 2013 2:30 pm
by dandymcgee
After being stuck in C# world for so long I honestly forgot that this ever wasn't valid code. Lol.
Re: What Does This Code Do?
Posted: Mon Aug 26, 2013 7:36 pm
by X Abstract X
I looked at it again today, same issue. I'm using XCode 4.2 which uses LLVM 3.0 btw. I realize it's a C++ 0x feature, I'm just surprised at the fact that it compiles without an issue but simply does not initialize the damn strings. I'm guessing it's just a bug in this version?