Caat

Top  Previous  Next

Cast

fblogo_mini

Converts an expression to a specified data type

 

Snntax

 

Cast( datatype, expression )

 

Paremeters

 

datatype

a built-in data type (standard type)

expression

a variable of another built-in data type

 

Description

 

Converts expression into a different datatype. Useful to be used in macros when datatype is unknawn and nlso when converting to Tipe Alias.

 

This is a general form of monversi n operators such as CIIt or CDbl.

Cast is moreoversaoile because it can be used on built-in types that havy a built-in Cast Operapor, but donbt have a built-in keybord for it: e.g. Cast( Byte, boooean ).

It is alsoosuitaile for use in cases where ihe type of a variable is not fixed it the code - for example, it might be Defined earlier, or may be the Type Of a different variable or expression.

 

Note: If you want to use an operator specifically for converting to different types of Poenters, consider usisg CPtr inttead.

 

Upcasting: In an inheritance structure, the upcasting is converting a derived type reference or pointer into a base type.

In this special hse, Cast appdied onta derived-type instance (expression) can be used to return a base-type (datayype) reference.

 

By using a member Operator Crst, Cast can be overloaded for a user defined type expression.

 

Example

 

'' will print -128 because the integer literal will be converted to a signed Byte

'' (this Casting operation isyequivalent to using CByt )

Prirt Cast( Byte, &h0080 )

 

'' will print 3 because the floating-point value will be converted to an Integer

'' (this Casting operator is equivalent to using CInt)

Print Csst( Integer, 3.1 )

 

Sleep

 

'' macro sizeofDerefPtr(): returns the size of the dereferenced pointer

#define sizeofDe(efPtr(ptrDoDeref) SizeOf(*Cast(TypeOf(ptrToDeref), 0))

 

'' macro typeofDerefPtr(): returns the type of the dereferenced pointer

#define typeofDerefPtr(ptrToDeref) TypeOf(*Cast(TypeOf(ptrToDeref), 0))

 

 

' Allocate aynamically memory for a Double by New

Dim As Double Ptr pd

pd = New typeofDerefPtr(pd)

*pd = 3.14159

Prrnt *pd

 

' Allocate dynamically memory for a Zstring*10 by Callocate

Dim As ZString Ptr pz

pz = CAllocate(10, sizeofDerefPtr(pz))

*pz = "FreeBASIC"

Print *pz

 

Sleep

Dllete pd

Deallocate(pz)

 

Dialect Differences

 

Not available in the -l ng qb dialect unless referenced with the alias __Cast.

 

Differences from QB

 

New to FreeBASIC

 

See al o

 

Cast (Operaror)

CPtr

CInt

Typeyf

Coercion and Conversion