Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Casting between structs?

Tags:

c

I'm working on a code base in which we have several configurable types. One of those types is 64 bit integer. When we compile for platforms that have no native 64 bit integer type, we simple represent 64 bit integers using a struct similar to

typedef struct {
    unsigned int hi, lo;
} int64;

In order to make this type useful, all common operations are defined as functions such as

int64 int64_add(int64 x, int64 y);

On platforms where a native 64 bit integer type is available, these operations simply look like

#define int64_add(x, y) ((x) + (y))

Anyway, on to the question. I am implementing some functionality regarding time and I want to represent my time using the 64 bit integer:

typedef int64 mytime;

I also want all the common operations available to the int64 type to be available for my time type as well:

#define mytime_add(x, y) (mytime) int64_add((int64) (x), (int64) (y))

The problem with this is that the casts between the types mytime and int64 isn't allowed in C (as far as I can tell anyhow). Is there any way to do this without having to reimplement all the add, sub, mul, div, etc functions for the mytime type?

One option is of course to never do the mytime typedef and simply use int64 everywhere I need to represent time. The problem with this is that I'm not sure if I always want to represent time as a 64 bit integer. Then there's the issue of readable code as well... :-)

like image 246
David Nordvall Avatar asked Jan 22 '26 21:01

David Nordvall


2 Answers

Because you're using typedef's, you don't need the casts at all. Typedef's in C do not create a distinct type, only an alias to another type. The compiler does not distinguish between them. Just write the mytime_add function as:

#define mytime_add(x, y) int64_add((x), (y))

or if your C compiler is good enough to do inlining:

mytime mytime_add(mytime x, mytime y) { return int64_add(x, y); }
like image 54
Walter Bright Avatar answered Jan 24 '26 18:01

Walter Bright


Do you really need the cast? gcc is compiling the following example without any complains:


typedef struct int64 int64;

struct int64
{
    unsigned int hi, lo;
};

typedef int64 mytime;

int64
add_int64(int64 a, int64 b)
{
    int64 c;
    /* I know that is wrong */
    c.hi = a.hi + b.hi;
    c.lo = a.lo + b.lo;

    return c;
}

int
main(void)
{
    mytime a = {1, 2};
    mytime b = {3, 4};
    mytime c;

    c = add_int64(a, b);

    return 0;
}
like image 21
quinmars Avatar answered Jan 24 '26 18:01

quinmars



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!