Title
Bit-fields and narrowing conversions
Status
c++23
Section
9.4.5 [dcl.init.list]
Submitter
Tim Song

Created on 2022-09-10.00:00:00 last changed 16 months ago

Messages

Date: 2022-10-07.20:36:40

Proposed resolution (approved by CWG 2022-10-07):

Change in 9.4.5 [dcl.init.list] bullet 7.4 as follows:

A narrowing conversion is an implicit conversion

  • ...
  • from an integer type or unscoped enumeration type to an integer type that cannot represent all the values of the original type, except where
    • the source is a bit-field whose width w is less than that of its type (or, for an enumeration type, its underlying type) and the target type can represent all the values of a hypothetical extended integer type with width w and with the same signedness as the original type or
    • the source is a constant expression whose value after integral promotions will fit into the target type, or
  • ...
Date: 2022-11-15.00:00:00

[Accepted as a DR at the November, 2022 meeting.]

Consider:

struct C {
  long long i : 8;
};

void f() {
  C x{1}, y{2};
  x.i <=> y.i; // error: narrowing conversion required (7.6.8 [expr.spaceship] bullet 4.1)
}

The rules for narrowing conversions in 9.4.5 [dcl.init.list] paragraph 7 consider only the source type, even though integral promotions can change the type of a bit-field to a smaller integer type without loss of value range according to 7.3.7 [conv.prom] paragraph 5:

A prvalue for an integral bit-field (11.4.10 [class.bit]) can be converted to a prvalue of type int if int can represent all the values of the bit-field; otherwise, it can be converted to unsigned int if unsigned int can represent all the values of the bit-field. If the bit-field is larger yet, no integral promotion applies to it. If the bit-field has enumeration type, it is treated as any other value of that type for promotion purposes.

There is implementation divergence in the handling of this example.

History
Date User Action Args
2023-07-16 13:00:43adminsetstatus: open -> c++23
2023-07-16 13:00:43adminsetstatus: drwp -> open
2023-02-18 18:43:04adminsetstatus: dr -> drwp
2022-11-25 05:14:04adminsetstatus: ready -> dr
2022-10-07 20:36:40adminsetmessages: + msg6948
2022-10-07 20:36:40adminsetstatus: open -> ready
2022-09-10 00:00:00admincreate