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 :(

1 Answer 1

4

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."
    };
}
Sign up to request clarification or add additional context in comments.

1 Comment

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.

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.