Reputation: 357
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)?
Upvotes: 0
Views: 237
Reputation: 181859
For the built-in datatypes (e.g.
int
,float
etc), there are built-in 'rules' for casting
No, there are not. "Casting" is the effect of typecast operator, which is a type conversion. There are some conversions that are performed without casting, but no casts are performed without a cast operator.
Is there any way to define custom 'casting rules' for my own datatypes defined by typedefs
Typedefs are just aliases for types. They have nothing to do with defining a new type.
If you create a typedef
alias for a type that affords automatic conversions then those will apply equally to objects and values whose type is described via the typedef
. But as far as the language spec goes, there are automatic conversions only where the spec says there are. Some C implementations extend that set -- for example, to provide automatic conversions between integers and pointers -- but no C implementation I know allows the code being compiled to define new automatic conversions. C++ is over yonder.
Upvotes: 2
Reputation: 225767
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;
}
Upvotes: 2