Next: , Previous: , Up: Programming   [Contents][Index]

6.13 Casts

Asymptote implicitly casts int to real, int to pair, real to pair, pair to path, pair to guide, path to guide, guide to path, real to pen, pair[] to guide[], pair[] to path[], path to path[], and guide to path[], along with various three-dimensional casts defined in three.asy. Implicit casts are automatically attempted on assignment and when trying to match function calls with possible function signatures. Implicit casting can be inhibited by declaring individual arguments explicit in the function signature, say to avoid an ambiguous function call in the following example, which outputs 0:

int f(pair a) {return 0;}
int f(explicit real x) {return 1;}


Other conversions, say real to int or real to string, require an explicit cast:

int i=(int) 2.5;
string s=(string) 2.5;

real[] a={2.5,-3.5};
int[] b=(int []) a;
write(stdout,b);     // Outputs 2,-3

In situations where casting from a string to a type T fails, an uninitialized variable is returned; this condition can be detected with the function bool initialized(T);

int i=(int) "2.5";
assert(initialized(i),"Invalid cast.");

real x=(real) "2.5a";
assert(initialized(x),"Invalid cast.");

Casting to user-defined types is also possible using operator cast:

struct rpair {
  real radius;
  real angle;

pair operator cast(rpair x) {
  return (x.radius*cos(x.angle),x.radius*sin(x.angle));

rpair x;

write(x);            // Outputs (0.866025403784439,0.5)

One must use care when defining new cast operators. Suppose that in some code one wants all integers to represent multiples of 100. To convert them to reals, one would first want to multiply them by 100. However, the straightforward implementation

real operator cast(int x) {return x*100;}

is equivalent to an infinite recursion, since the result x*100 needs itself to be cast from an integer to a real. Instead, we want to use the standard conversion of int to real:

real convert(int x) {return x*100;}
real operator cast(int x)=convert;

Explicit casts are implemented similarly, with operator ecast.

Next: , Previous: , Up: Programming   [Contents][Index]