문제

I have the following struct:

struct holder {
  int cause;
  int agent:1, group:1, supervisor:1, defer:1;
};

Klocwork complains at the int agent:1 ... line saying: Bit field 'agent' has one bit and is signed. Signed one bit field, CWARN.SIGNEDBIT.

I don't understand why the integer being signed would make any difference. I realise that for a signed integer the leftmost (most significant) bit is used to determine whether integer is positive or negative but in case of bit fields that surely wouldn't matter???

Klocwork developer web site says:

Signed bitfields require at least two bits, and the two possible values of the field are -1 and 0. Although it is safe to check a 1-bit signed bitfield for 0, using it as a Boolean flag, other arithmetic operations may yield unexpected results.

Can someone please explain why integer must be unsigned in this case?

도움이 되었습니까?

해결책

If you use the value as a flag, it's more logical to store it as unsigned since the normal expression would be 1 and 0, not -1 and 0. A logic expression in C also returns 1 if true, not -1

Another problem is that if you use signed bit fields, it may take many more instructions to sign extend the value instead of just masking off the unneeded bits.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top