views:

38

answers:

1

I got the following code, wishing to wrap a group of strings nicely in a namespace:

namespace msgs {

    const int arr_sz = 3;
    const char *msg[arr_sz] = {"blank", "blank", "blank" };

    msg[0] = "Welcome, bla bla string 1!\n";
    msg[1] = "Alright, bla bla bla..";
    msg[2] = "etc.";

}

The code inside works nicely inside a function, but I don't know how to return an array from it. The namespace idea LOOKS fine, but it returns on the last three lines: error: expected constructor, destructor, or type conversion before ‘=’ token

Why can't I define the array inside a namespace, do I need to do something first?

It's nice because I can call it like printf(msgs::msg[1]) etc. I want to do this I just can't wrap my head around what's wrong :(

+2  A: 

You can define the array inside the namespace:

// this is legal
namespace msgs {
    const char *msg[] = {"blank", "blank", "blank" };
}

What you can't do is have a statement outside of a function:

// this is a statement, it must be inside a function
msg[0] = "Welcome, lets start by getting a little info from you!\n";

So to fix your code, just use the correct string in the definition:

namespace msgs {
    const char *msg[] = {
        "Welcome, lets start by getting a little info from you!\n",
        "Alright, bla bla bla..",
        "etc."
    };
}
R Samuel Klatchko
I caught this JUST after I posted, I forgot I was initializing the arrays before trying modifying them, just wanted to double check with an answer here on why I couldn't define it.
John D.