views:

126

answers:

2

For purposes of type checking I would like to define a function on the lines of

void myfunc(type1 a, type2 b)
{
...
}

where type1 and type2 are both typedefed to uint8_t. So far so good, but for sanity and checking purposes (think DbC) I would like to prevent the function being called with a type2 value for the first parameter or a type1 for the second. Sadly, C's implicit typecasting is against me here. Does anyone know of a way?

+6  A: 

You could wrap the two types in a Struct.

typedef struct {
    uint8_t data;
} type1;

typedef struct {
    uint8_t data;
} type2;

Edit: I don't like it because you now have to use a.data instead of a

nuriaion
why do you say it is not nice ? The intention is clear: the types are different.
Alexandre C.
Yes, this is right. Despite the name, `typedef` doesn't actually introduce a new type in C - only `struct` and `union` do that.
caf
I agree that having to use a.data is slightly inconvenient, other than that it seems quite clean to me. Thanks!
michaeljt
Sorry, read that last comment as "although it is slightly inconvenient, it still seems quite a clean solution".
michaeljt
A: 

I think you can wrap your types using struct and then pass pointer to these structs.

Daniel Băluţă
You can even pass the structs itself instead of pointers. Structs don't have to be passed by ref, they can be passed by value (in that case the whole struct content is copied; so not a good idea for big structs). Passing them by value has no overhead, if the struct itself is not bigger than a pointer reference would be in size.
Mecki