Unchecked_Conversion in Ada

Can someone please let me understand about using untested conversion in Ada language. I've tried PDF and web, but none of this gives me a clear picture for me.

  Now i have a small piece of code shown below:

    subtype Element4_Range is integer range 1..4;
    subtype Element3_Range is integer range 1..3;
    subtype Myarr_Range is integer range 1..10;
    type Myarr3_Type is array (Myarr_Range) of Element3_Range;
    type Myarr4_Type is array (Myarr_Range) of Element4_Range;
    Myarr3 : Myarr3_Type;
    Myarr4 : Myarr4_Type := (1,2,3,3,1,3,2,1,2,1);
    Count_1 : Integer := 0;
    Count_2 : Integer := 0;
    Count_3 : Integer := 0;
    *function To_Myarr3 is new Unchecked_Conversion(Myarr4_type,Myarr3_type);*

      

Now my doubt is, what exactly does the Myarr3 function do?

+2


a source to share


2 answers


Replication Unchecked_Conversion

copies the bytes of the original value to the target without checking if this is reasonable. Some compilers will warn (depending on compilation options) if the values ​​are of different sizes.

Element3_Range

both Element4_Range

are based on Integer

and will use the same number of bytes; so both array variables ( Myarr3

, Myarr4

) will need the same number of bytes (usually 40).

You can write

Myarr3 := To_Myarr3 (Myarr4);

      

Be that as it may, nothing bad will happen, because all the values ​​that you used to initialize Myarr4

are legal values Element3_Range

.



However, if you have

Myarr3 := To_Myarr3 (Myarr4'(1, 2, 3, 4, others => 1));

      

you end up Myarr3(4)

with an out-of-range value Element3_Range

, and the compiler has no reason to believe it might not be valid. This can lead to Constraint_Error

down the line.

You can force yourself to check:

if not Myarr3 (4)'Valid then
  -- handle the error case

      

+3


a source


I had one co-worker who claimed unchecked_conversion

to be named "Unchcked_Copy". All it does is copy an object of one type to an object of another type.

Thus, your routine To_Myarr3

will take an array of type Myarr4 as a parameter, pretend it is an array of type Myarr3, and then copy each element into it to the left side of your expression.



If you want to change your kind of object from one type to another without copying the whole heck around, you can instead use Unchecked_Conversion on the accessor types for them (so you only copy the pointer to them). Another method uses for object_name'address use at

to overlay one on top of the other (however, they can both be initialized, which can be bad). But the really best way is to design the types of your system so that you never have to use Unchecked_Conversion .

+2


a source







All Articles