Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How are conversions applied to bit-field types in conditional operators?

The following code prints int when compiled for x86_64 with Clang, and unsigned int with GCC.

I am not sure which (if either) is correct.

#include <stdio.h>
struct s {
    unsigned int x : 1;
};

template<typename T>
void f(T) {}

template<> void f<int>(int) {
    printf("int\n");
}

template<> void f<unsigned int>(unsigned int) {
    printf("unsigned int\n");
}

struct s r;
int main()
{
    f(0 ? r.x : 0);
}

If we replace the conditional with (r.x + 0) both compilers say the type is signed.

The C++ standard section expr.cond has a number of rules for conversion, but none of the cases seem to cover the issue of a conversion between a glvalue and a prvalue of different types.

Is it implementation-defined whether unsigned bitfields are promoted to signed ints?

like image 918
Tjaden Hess Avatar asked Sep 22 '20 22:09

Tjaden Hess


People also ask

Which operator can be used to do type conversions?

operator int(); ... }; The operator overloading defines a type conversion operator that can be used to produce an int type from a Counter object. This operator will be used whenever an implicit or explict conversion of a Counter object to an int is required. Notice that constructors also play a role in type conversion.

How do bit fields work in C?

In C, we can specify size (in bits) of structure and union members. The idea is to use memory efficiently when we know that the value of a field or group of fields will never exceed a limit or is within a small range. For example, consider the following declaration of date without the use of bit fields.

What is a bit field Why are bit fields used with structures?

These space-saving structure members are called bit fields, and their width in bits can be explicitly declared. Bit fields are used in programs that must force a data structure to correspond to a fixed hardware representation and are unlikely to be portable.

How do bit fields work?

In programming terminology, a bit field is a data structure that allows the programmer to allocate memory to structures and unions in bits in order to utilize computer memory in an efficient manner. Since structures and unions are user-defined data types in C, the user has an idea of how much memory will they occupy.


1 Answers

Clang is correct: the usual arithmetic conversions are applied just as for + ([expr.cond]/7.2) and promote the bit-field to int because it can represent all its values ([expr.arith.conv]/1.5, [conv.prom]/5, noting that the lvalue-to-rvalue conversion has already been applied ([expr.cond]/7, before the bullets)).

like image 53
Davis Herring Avatar answered Oct 22 '22 16:10

Davis Herring