6 Structures
They are defined with struct and opt_struct keywords.
struct s {
int a;
string b;
}
is roughly equivalent of C's:
typedef struct {
int a;
char *b;
} *s;
So, name s
can be used (only) without any struct or
opt_struct. For example, this piece of code uses
structure definition above:
string f(s foo)
{
foo.a = 5;
return foo.b;
}
You should note, that structures are passed by pointer (or by reference
if you prefer C++ naming style), therefore changes made to struct inside
function are reflected in state of it on the caller side, hence:
s x;
...
x.a = 10;
f(x);
// x.a is 5 here
Fields of structure can be accessed with `.' operator, there is no `->'
operator.
6.1 What's opt_struct?
struct value is always valid, i.e. it has to be initialized
with object instance, before it is used, and you
cannot assign null pointer to it.
opt_struct can be null. You still have to initialize
it before, it is used, but you can do it with null keyword.
You can also assign null to it later on.
This involves runtime check on each access to opt_struct
value. When you try to access opt_struct value, that is
null, Null_access
exception is raised. This behavior
can be controlled with compiler switch.
6.2 Assignment to structures
If you do:
void f(s1 x)
{
s1 y;
y = x;
y.fld = 0; // here you also modify x.fld
}
In general assigning values other then int
's, bool
's and
float
's copies pointer, not content, i.e. makes an alias of an object.
6.3 Structure initializers
When initializing structures one has to spell field name along with
expression initializing it. For example:
struct foo {
int bar;
string baz;
}
void f()
{
foo qux = ({ bar = 1, baz = "quxx" });
}
({ ... }) is also normal expression, for instance:
void f()
{
foo(({ bar = 1, baz = "qux" }));
}