Home>
Question

scoped enum type variables are recognized as values ​​other than the enumerator, but if you define the following functionfunc, you will get the following warning:

Visual Studio:Warning: C4715: Some control paths do not return a value.
GCC:warning: control reaches end of non-void function [-Wreturn-type]

Is this a case where in some case there is a case where no if statement is caught and not returned?

enum class Type
{
    A,
    B,
    C,
};
int func (Type type)
{
    if (type == Type :: A)
        return 1;
    else if (type == Type :: B)
        return 2;
    else if (type == Type :: C)
        return 3;
}
int main ()
{
    func (Type :: A);
}
Environment
  • C ++ 11
c++
  • Answer # 1

    Hello.

    I think the compiler hasn't just checked that it can't take values ​​other than the enumerator.
    In switch-case, I think that there were some compilers that checked that much.
    Checking with an if statement is quite difficult, but it is easy with switch-case.

  • Answer # 2

    Even though it is aenum class, the contents are integers, so it was possible to usestatic_castto inject values ​​that are not related to brute force. I have n’t checked.)

    # include
    using namespace std;
    enum class Type
    {
        A,
        B,
        C,
    };
    int main (void) {
        // out of range because there are no 7
        Type t = static_cast(7);
        // Ichio "7" returns as it is
        cout<(t)<

    Example of operation in paiza.io

    >

    Is there such a pattern?

    enum class Type
    {
        A = 2,
        B = 7,
        C = 9,
    };
    // Non-local and not explicitly writing initial value
    Type t;// The value is not initialized to 0
    int main ()
    {
      std :: out<(t)<