Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bit-fields "In-class initialization" results in "error: lvalue required as left operand of assignment"

struct bitfield {
  int i = 0;  // ok
  int j : 8 = 0;  // error: lvalue required as left operand of assignment
};

What is the correct syntax to initialize bit-fields using C++11 "in-class initialization" feature?

like image 601
iammilind Avatar asked May 13 '13 11:05

iammilind


4 Answers

This was raised as Core Issue 1341 to the C++ standard, but was rejected by the C++ Core Working Group in October 2015 as NAD ("not a defect") - see http://open-std.org/JTC1/SC22/WG21/docs/cwg_closed.html#1341

like image 104
Ville Voutilainen Avatar answered Nov 01 '22 10:11

Ville Voutilainen


What is the correct syntax to initialize bit-fields using C++11 "in-class initialization" feature?

You cannot initialize bit-fields in-class. Paragraph 9.2 of the C++11 Standard specifies the grammar for class member declarators:

[...]

member-declarator:

declarator virt-specifier-seq(opt) pure-specifier(opt)

declarator brace-or-equal-initializer(opt)

identifier(opt) attribute-specifier-seq(opt): constant-expression

As you can see, declarators for bit-field members cannot be terminated by a brace-or-equal-initializer.

like image 33
Andy Prowl Avatar answered Nov 01 '22 12:11

Andy Prowl


You can write a constructor with initializer list to give default values to your bitfields.

struct bitfield {
  int i;
  int j : 8;

  bitfield() : i(0), j(0) {};
};

You can also create read-only fields with default values.

struct _UserRegister1
{
  uint8_t _RES0 : 1;
  const uint8_t reserved1 : 1;
  uint8_t _HTRE : 1;
  const uint8_t reserved2 : 3;
  uint8_t _VDDS : 1;
  uint8_t _RES1 : 1;

  _UserRegister1() : reserved1(1), reserved2(7) {};
};
like image 2
Bence Kaulics Avatar answered Nov 01 '22 11:11

Bence Kaulics


C++11 doesn't provide any syntax for default initializing bitfields, but C++ 20 does.

That means your example compiles fine when your C++ compiler supports C++20:

struct bitfield {
  int i = 0;      // ok
  int j : 8 = 0;  // ok since C++20
  int k : 8 {0};  // ditto
};

Note that you might need to explicitly enable C++20 support, e.g. with -std=c++20 when using a not too recent GCC/Clang version.

like image 2
maxschlepzig Avatar answered Nov 01 '22 10:11

maxschlepzig