PTypes: variant: assignments and typecasts

Top: Basic types: variant: Assignments and typecasts

Variants may hold values of the following types:

- 64-bit integer (large)
- boolean (bool)
- floating point (double)
- string
- associative array of variants
- reference to an object derived from component
- unassigned (no type)

Variants are compatible with variables and constants of all numeric types, the string type and a pointer to component, which means, you can assign any of these values to a variant object and vice versa, including passing as parameters to functions. The type of a variant can be changed at run-time by simply assigning a new value to it.

By default variants are initialized to an unassigned state, which is the same as calling clear() for a variant object.

You may store datetime values in variants, since datetime is equivalent to large in PTypes. Besides, arbitrary binary data can be stored in a dynamic string and then assigned to a variant.

The variant class declares (or rather, overloads) all possible typecast operators to other fundamental data types. These typecast operators always try to return some value, even when it is not sensible. Below is a list of rules for typecasts that may make sense in your program, leaving the other less meaningful cases as 'unspecified'. Although variants store integers as 64-bit values, for simplicity we use the word int in this list.

- integers and floating point variants are compatible and mutually castable in a manner similar to the C language rules
- int to bool: returns true if the value is non-zero
- int to string: returns the string representing the value in ASCII form
- bool to int: returns 0 or 1
- bool to string: returns "0" or "1"
- string to int: converts the string to an integer; no spaces are allowed before or after the number; returns 0 if the string does not represent a number
- string to float: similar to string-to-int, converts the string to a floating-point value
- string to bool: returns true if the string is not empty
- array to bool: returns true if the array is not empty
- (component*) to bool: returns true if the pointer is not NULL
- unassigned variants return 0, false, 0.0, empty string, empty array or NULL when trying to cast to int, boolean, floating point, string, array or reference, respectively.

Typecast operators never affect the actual value of a variant object.

When trying to cast a variant to signed or unsigned 32-bit int, the typecast operator first casts the value to 64-bit large according to the rules above, and then checks the resulting value. If the value is out of range, an exception of type (evariant*) is raised. You may always cast variants to large to get rid of extra exception handling code in your program.

See also: string, datetime, unknown & component, Arrays, Object references, Utilities

PTypes home