Issue
I have the following typedefs in my code:
#define FOO_OFF 0
#define FOO_ON 1
typedef uint8_t foo;
#define BAR_NO 0
#define BAR_YES 1
#define BAR_UNKNOWN 255
typedef uint8_t bar;
Those two types, although they have the same underlying type, they do not carry the same information.
And actually, I would like to get a warning if anyone in the code does something like:
foo foovar = FOO_OFF;
void get_bar(bar *outvar)
{
// assigning the bar variable a foo variable content
*outvar = foovar;
}
I could not find any such warning option in gcc, I have come accross -Wconversion
but this warns only if there is a chance of losing information which is not the case in my example.
Does anyone know if there is something I can do? Obviously, it should be possible to cast when a type change is really needed.
Solution
Short answer is no, you can't do this. typedef
declare an alias, not a new type, so any compiler respecting the standard cannot have the feature you want right now.
However, you can achieve it, by introducing a new type, using an enum, or a struct.
If you're in C, you will be able to cast from one enum to the other easily.
Because the address of the first element of a struct is also the address of a struct, you would be able to cast it from and to int8 or another struct, by casting the struct address, then de-referencing the pointer with it's new type. (*((dest_type *)&value)
)
Answered By - Phantomas Answer Checked By - Pedro (WPSolving Volunteer)