Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Define rules for casting to custom datatypes in C

For the built-in datatypes (e.g. int, float etc), there are built-in ‘rules’ for casting: e.g.

int x, float y;
x = 3;
y = x;

will produce y = 3.000000.

Is there any way to define custom ‘casting rules’ for my own datatypes defined by typedefs?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Say I have a struct rational representing a rational number. I would like to be able to cast int variables to rational such that the denominator field is set to 1 and the numerator is equal to the initial int. I.e. if I do:

typedef struct rational{int num; int denom;} rational;
int x, rational y;
x = 3;
y = x;

I want to get y.num = 3 and y.denom = 1.

Can arbitrary functions be defined to control the behaviour when casting to/from user-defined datatypes?

Failing that, is it possible to set a ‘default’ value for a subset of a struct’s members (such that that member can be optionally skipped when assigning a value to a variable of that type, defaulting to the set value)?

>Solution :

Unlike C++ which allows you to overload the typecast operator and assignment operator, C doesn’t allow you to define your own casts or implicit conversions.

You’ll need to write a function that performs the conversion. For example:

rational int_to_rational(int x)
{
    rational r = { x, 1 };
    return r;
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading