C++ Logo

std-discussion

Advanced search

Relative to the underlying type of unscoped enumerations

From: Vladimir Grigoriev <vlad.moscow_at_[hidden]>
Date: Fri, 25 Apr 2025 01:38:56 +0300
In the C++20 Standard there is written (9.7.1 Enumeration declarations):
 
7 For an enumeration whose underlying type is not fixed, the underlying type is an integral type that can represent all the enumerator values defined in the enumeration. If no integral type can represent all the enumerator values, the enumeration is ill-formed. It is implementation-defined which integral type is used as the underlying type except that the underlying type shall not be larger than int unless the value of an enumerator cannot fit in an int or unsigned int . If the enumerator-list is empty, the underlying type is as if the enumeration had a single enumerator with value 0.
 
However if to run this simple program
 
#include <iostream>
#include <type_traits>

int main()
{
    int vals[]{ 2,3,5,7,11 };
    enum { N = sizeof vals / sizeof vals[0] };

    std::cout << std::boolalpha;
    std::cout << "std::is_same_v<std::underlying_type_t<decltype( N )>, size_t> = "
              << std::is_same_v<std::underlying_type_t<decltype( N )>, size_t> << '\n';
}
 
then the MS VS2022 outputs true though size_t is an alias for the type unsigned long long and the constant value used as an initializer of the enumerator N at least can fit in an object of the type unsigned int.
 
Is it a bug of the MS VS2022 C++ compiler?
 
With best regards,
(Vlad from Moscow)
 
You can meet me at http://cpp.forum24.ru/ or www.stackoverflow.com or http://ru.stackoverflow.com

Received on 2025-04-24 22:39:24