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?
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)?
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;
}