Home > Backend Development > C++ > How to Retrieve Enum Values as Text in C ?

How to Retrieve Enum Values as Text in C ?

DDD
Release: 2024-11-30 07:56:12
Original
899 people have browsed it

How to Retrieve Enum Values as Text in C  ?

Retrieving Enum Values as Text in C

In C , the default behavior for printing enums is to output their numerical values. However, there are situations where it is desirable to retrieve the textual representation of an enum value.

Solutions Without if/switch:

Using a Map:

#include <map>
#include <string_view>

enum Errors { ErrorA = 0, ErrorB, ErrorC };

std::ostream& operator<<(std::ostream& out, const Errors value) {
    static const auto strings = []() {
        std::map<Errors, std::string_view> result;
#define INSERT_ELEMENT(p) result.emplace(p, #p);
        INSERT_ELEMENT(ErrorA);
        INSERT_ELEMENT(ErrorB);
        INSERT_ELEMENT(ErrorC);
#undef INSERT_ELEMENT
        return result;
    }();

    return out << strings[value];
}
Copy after login

Using an Array with Linear Search:

#include <string_view>

enum Errors { ErrorA = 0, ErrorB, ErrorC };

std::ostream& operator<<(std::ostream& out, const Errors value) {
#define MAPENTRY(p) {p, #p}
    const struct MapEntry {
        Errors value;
        std::string_view str;
    } entries[] = {
        MAPENTRY(ErrorA),
        MAPENTRY(ErrorB),
        MAPENTRY(ErrorC),
        {ErrorA, 0} // Placeholder for default case
    };
#undef MAPENTRY

    const char* s = 0;
    for (const MapEntry* i = entries; i->str; i++) {
        if (i->value == value) {
            s = i->str;
            break;
        }
    }

    return out << s;
}
Copy after login

Using a Switch/Case Statement:

#include <string>

enum Errors { ErrorA = 0, ErrorB, ErrorC };

std::ostream& operator<<(std::ostream& out, const Errors value) {
    return out << [value]() {
#define PROCESS_VAL(p) case(p): return #p;
        switch (value) {
        PROCESS_VAL(ErrorA);
        PROCESS_VAL(ErrorB);
        PROCESS_VAL(ErrorC);
        }
#undef PROCESS_VAL
    }();
}
Copy after login

Test Case:

#include <iostream>

int main() {
    std::cout << ErrorA << std::endl << ErrorB << std::endl << ErrorC;
    return 0;
}
Copy after login

The above is the detailed content of How to Retrieve Enum Values as Text in C ?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template