0

Is it safe to use an enum to index an array? For example:

void messageToCerr( QtMsgType type,
                const QMessageLogContext& context,
                const QString& msg
              ) {
QVector<QString> typeName = {"Debug", "Warning", "Critical", "Fatal", "Info"};
QString output = QString( "[%1] %2" ).arg( typeName.at(type) ).arg( msg );
std::cerr << output.toStdString() << std::endl;
if ( type == QtMsgType::QtFatalMsg ) {

    abort();
}

}

Is using "type", which is

enum QtMsgType { QtDebugMsg, QtInfoMsg, QtWarningMsg, QtCriticalMsg, QtFatalMsg, QtSystemMsg }

like an array (vector) index is safe? I read that traversing enum like array is unsafe.

penny
  • 67
  • 6

1 Answers1

1

Yes, what you are doing is safe given your definitions, but I'd suggest declaring/defining the vector at the time your creating the enum. So something like:

enum QtMsgType { QtDebugMsg, QtInfoMsg, QtWarningMsg, QtCriticalMsg, QtFatalMsg, QtSystemMsg };
QVector<QString> typeName = {"Debug", "Warning", "Critical", "Fatal", "Info"};

This will also make it abundantly clear that your vector is wrong! Notice how the enum has Debug, Info, Warning, ... and your vector is Debug, Warning, Critical, .... Furthermore, there's no point in using a resizeable structure when it's a constant. As such, you can just have an array. Putting that all together would look like:

enum QtMsgType { QtDebugMsg, QtInfoMsg, QtWarningMsg, QtCriticalMsg, QtFatalMsg, QtSystemMsg };
QString typeName[] = {"Debug", "Info", "Warning", "Critical", "Fatal"};

Another option would be to overload the << operator for streams for your enum and then stick all of the logic in there.

For more options, take a look at this thread: How to convert an enum type variable to a string?

scohe001
  • 15,110
  • 2
  • 31
  • 51
  • Side note there isn't much value in using a re-sizable data structure like `QVector` for a fixed size list. I'd add a `QtMsg_Last` or similar as the last entry in the enum. This gives you an easy value to use in a bounds check and a constant to use as the size of a `std::array`. – user4581301 Jan 14 '20 at 22:25
  • Good call @user. I've edited the array implementation in. – scohe001 Jan 14 '20 at 22:29