Don't use ~0
(which is always a full int
), but ~v.bar
, which is the right size and can be combined like so:
v.bar |= ~v.bar; // or,
v.bar ^= ~v.bar;
should do the trick, for any size.
Unfortunately you can't nicely wrap it in a function since you can't bind references to bitfields. You'd either need to make it a function on Foo&
, or use a macro.
PS. I tried this quickly before posting with coliru, and just re-checked locally with GCC (g++) 5.3.1 and 6.2.0 - neither issue any diagnostic with -Wall
.
PPS.
With this test code, GCC produces a diagnostic only for the unsigned member:
struct Foo {
int i : 2;
unsigned int u : 30;
};
void bar() {
Foo f {0, 0};
f.i ^= ~f.i; // OK
f.u |= ~f.u; /* warning:
large integer implicitly truncated to unsigned type [-Woverflow]
*/
}
So although I'd also usually prefer unsigned integers for bitfields or for bitwise manipulation, g++ is happier and quieter with int
here.
v.bar = UINT_MAX;
? – M.M Feb 13 '17 at 11:19signed int bar
if you specifically want a signed field. – M.M Feb 13 '17 at 11:23