#Using struct member in switch case

12 messages · Page 1 of 1 (latest)

hallow coral
#

I have a struct and it's instances like so (there are some other members in my code): ```cpp
struct element {
int id;
}

const element someElement = { 12 };

And somewhere later in the code, I'd like to use it like this: ```cpp
switch(id)
{
  case someElement.id:
    //stuff
  break;
}

However, I get an error saying attempt to access run-time storage on the case (specifically the someElement part is underlined). How/can I do it like this or will I have to hardcode the IDs into the switch?

Thanks.

fair isleBOT
#

When your question is answered use !solved to mark the question as resolved.

Remember to ask specific questions, provide necessary details, and reduce your question to its simplest form. For more information use !howto ask.

keen void
#

so the compiler knows that its compile time constant

hallow coral
#

So I need to replace const with constexpr or do something like this: const constexpr someElement = { 12 };

keen void
#

also in general you should prefer to use constexpr instead of const in c++ for that kind of constants

hallow coral
#

Got it.

#

One of the members is a std::wstring and I'm getting an error now: cannot call non-constexpr function std::basic_string. What does it mean?

hallow coral
#

Using wstring_view fixed it.

#

!solved

fair isleBOT
#

Thank you and let us know if you have any more questions!

#

[SOLVED] Using struct member in switch case