Skip to content

Commit

Permalink
Updates to the any documentation.
Browse files Browse the repository at this point in the history
  • Loading branch information
lerno committed Jul 19, 2024
1 parent bfc8da8 commit a802d03
Showing 1 changed file with 21 additions and 4 deletions.
25 changes: 21 additions & 4 deletions src/content/docs/references/docs/types.md
Original file line number Diff line number Diff line change
Expand Up @@ -189,13 +189,18 @@ e.g. `typeid a = Foo.typeid;`. This value is pointer-sized.
### The `any` type

C3 contains a built-in variant type, which is essentially struct containing a `typeid` plus a `void*` pointer to a value.
It is possible to cast the any pointer to any pointer type, which will return `null` if the types don't match,
or the pointer value otherwise.
While it is possible to cast the `any` pointer to any pointer type,
it is recommended to use the `anycast` macro or checking the type explicitly first.

int x;
any y = &x;
double *z = (double*)y; // Returns null
int* w = (int*)y; // Returns the pointer to x
int* w = (int*)y; // Returns the pointer to x
double* z_bad = (double*)y; // Don't do this!
double! z = anycast(y, double); // The safe way to get a value
if (y.type == int.typeid)
{
// Do something if y contains an int*
}

Switching over the `any` type is another method to unwrap the pointer inside:

Expand All @@ -221,6 +226,18 @@ Switching over the `any` type is another method to unwrap the pointer inside:
case int:
// w is int here
}
// Finally, if we just want to deal with the case
// where it is a single specific type:
if (z.type == int.typeid)
{
// This is safe here:
int* a = (int*)z;
}
if (try b = *anycast(z, int))
{
// b is an int:
foo(b * 3);
}
}

`any.type` returns the underlying pointee typeid of the contained value. `any.ptr` returns
Expand Down

0 comments on commit a802d03

Please sign in to comment.