6

Is it ok to use initialization like this?

class Foo
{
public:
   Foo() : str("str") {}
   char str[4];
};

And this?

int main()
{
   char str[4]("str");
}

Both give me an error in gcc 4.7.2:

error: array used as initializer

Comeau compiles both.

1
  • clang also compiles both of these in C++03 mode. Commented Nov 3, 2012 at 6:46

3 Answers 3

5

In C++03, the non-static member array cannot be initialized as you mentioned. In g++ may be you can have an extension of initializer list, but that's a C++11 feature.

Local variable in a function can be initialized like this:

char str[] = "str"; // (1)
char str[] = {'s','t','r',0}; // (2)

Though you can mention the dimension as 4, but it's better not mentioned to avoid accidental array out of bounds.

I would recommend to use std::string in both the cases.

Sign up to request clarification or add additional context in comments.

2 Comments

Comeau compiles both in C++03 mode, why?
What's the justification for believing that character arrays can't be initialized this way? From what I read in the standard and the gcc bug database (see my answer) it looks to me like character arrays can be initialized this way.
5

This code is valid C++03 and gcc is simply not conformant here.

The language that allows this syntax for initializing character arrays is the same as allows it for any other type; there are no exceptions that would prohibit it from being used on character arrays. () and = initialization are equivalent in these cases and the character array should simply be initialized according to 8.5.2.

Here's a confirmed gcc bug report that covers this.

1 Comment

+1, indeed a gcc bug. gcc prints the error so genuinely that it appears as non-standard construct.
3

In C++03, that is not possible. Comeau might compile it because of non-Standard extension.

In C++11, you can do this:

Foo() : str({'s','t','r'}) {}       //C++11 only

Or, you may prefer this intead:

class Foo
{
public:
   Foo() {}
   char str[4] = "str"; //in-class initialization (C++11 only)
};

Also, you might consider using std::string or std::vector<char> irrespective of the version of C++ you're using.

3 Comments

Comeau is a strict ISO-conforming compiler, so i don't sure that this is an extension. Are you sure?
@NikitaTrophimov: I am dead sure that you cannot do that in C++03.
The fact that GCC rejects this has been confirmed as a bug in the GCC bug reporter.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.