I'm getting unexpected output in 2 different cases. The 1st deals with bitfields. The C++ standard has this line about integral promotions:
An rvalue for an integral bit-field (9.6) can be converted to an rvalue 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 an enumerated type, it is treated as any
other value of that type for promotion purposes.
This sounds like the value of a bitfield will always be treated as a signed int if the signed representation of the value will fit in the bits. This seems to hold true for my C compiler, but not my C++ compiler.
I tried storing a small negative value in a bitfield that has enough bits to store the sign bit and the value. But when I print out the bitfield, I always get a large number
In the example code below, I expect the output:
Code:
foo.x = -1
foo.y = -2
foo2.x = 31
foo2.y = 6
foo3.x = -1
foo4.x = 4294967295
But I get:
Code:
foo.x = 31
foo.y = 6
foo2.x = 31
foo2.y = 6
foo3.x = -1
foo4.x = -1
-------------------
The other issue I'm having is sort of similar. I'm trying to store 4294967295 into a float, but when I print it out, I get 4294967296. i've tried storing a few other large values like this and what's printed out is rarely the value I stored. I thought it might be because of some int to float conversion, so I tried 4294967295.0. Still no luck. Then I remember that defaults to a double so maybe that's the issue so I tried 4294967295.0f. Still no luck. Why can't I store the correct value here? I don't think it's an IEE format thing since I can use these values as floats on a calculator program.
The example code showing both issues is below.
Code:
#include <stdio.h>
typedef struct
{
signed char x : 5;
signed char y : 3;
}my_struct_t;
typedef struct
{
unsigned char x : 5;
unsigned char y : 3;
}my_struct2_t;
typedef struct
{
signed int x : 32;
}my_struct3_t;
typedef struct
{
unsigned int x : 32;
}my_struct4_t;
int main()
{
my_struct_t foo;
foo.x = -1;
foo.y = -2;
printf("foo.x = %d\n", foo.x);
printf("foo.y = %d\n", foo.y);
my_struct2_t foo2;
foo2.x = -1;
foo2.y = -2;
printf("foo2.x = %d\n", foo2.x);
printf("foo2.y = %d\n", foo2.y);
my_struct3_t foo3;
foo3.x = -1;
printf("foo3.x = %d\n", foo3.x);
my_struct4_t foo4;
foo4.x = -1;
printf("foo4.x = %d\n", foo4.x);
float f = 4294967295.0f;
printf("f = %f\n", f);
return 0;
}