C++ Logo

std-proposals

Advanced search

[std-proposals] A proposal on default enum initialization

From: <Aleksej.Penkov_at_[hidden]>
Date: Fri, 24 Mar 2023 14:32:30 +0000
Dear team,

I have a proposal to introduce an optional default-initializer for enum types.
For me it looks like currently an enum variable is by default initialized with a default value of the underlying type.

Code example:
#include <iostream>

enum TestEnum {
        good = -100,
        bad = 200
};

int main()
{
    TestEnum h;
    std::cout << h << std::endl;
    return 0;
}

Output: 0

The resulting value 0 is neither of the range ones.
The proposal is to have a way to specify the default one.

See the possible example below:
#include <iostream>

enum TestEnum {
        good = -100,
        bad = 200
default:
       bad
};

int main()
{
    TestEnum h;
    std::cout << h << std::endl;
    return 0;
}

Output: 200

Why I brought this up.
I've seen lots of code using kind of an enum below:
enum SomeEnum {
               Good = 0,
               SomeOption1,
               // some other values ...
               SomeOptionN,
               Invalid
};

Any class/struct having this enum as a member could potentially initialize it by default to Good leading to a customer of this thinking the object is in a 'Good' shape althought it's just in some 'default' one.
Changing that to:
enum SomeEnum {
               Good,
               SomeOption1,
               // some other values ...
               SomeOptionN,
               Invalid
default:
               Invalid
};
could prevent errors of using non-initialized objects.

Having the 'default' initializer could decrease a number of errors with incomplete/improper initialization.
Please let me know if this makes sense to your opinion.

Kind regards,
Aleksej Penkov

BMW Group
Aleksej Penkov
BMW Car IT
JC-6
Senior Software Engineer
Lise-Meitner-Straße 14
89081 Ulm

Telephone: +4973137804118
Mobile: +491742685058
Mail: aleksej.penkov_at_[hidden]<mailto:aleksej.penkov_at_[hidden]>
Web: https://www.bmw-carit.de

[cid:image001.png_at_[hidden]]
-------------------------------------------------------------------------
BMW Car IT GmbH
Management: Chris Brandt and Michael Böttrich
Domicile and Court of Registry: München HRB 134810
-------------------------------------------------------------------------



Received on 2023-03-24 14:32:33