Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unchecked_Conversion in Ada

Can anyone please make me clear about the use of unchecked conversion in the Ada language.I had tried the pdf and net but all doesn't give me a clear picture to 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 here is what does the function Myarr3 exactly do?

like image 779
maddy Avatar asked Jul 24 '26 02:07

maddy


1 Answers

An instantiation of Unchecked_Conversion copies the bytes of the source value to the target without checking whether this is sensible. Some compilers will warn (depending maybe on compilation options) if the values are of different sizes.

Element3_Range and Element4_Range are both based on Integer and will use the same number of bytes; so both of your array variables (Myarr3, Myarr4) will need the same number of bytes (40 typically).

You could write

Myarr3 := To_Myarr3 (Myarr4);

As it stands, nothing bad would happen because all the values you've used to initialise Myarr4 are legal as values of Element3_Range.

However, if you had

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

you'd end up with Myarr3(4) containing a value outside the legal range of Element3_Range, and with the compiler having no reason to believe that it might not be valid. This may well lead to Constraint_Errors down the line.

You could force a check yourself:

if not Myarr3 (4)'Valid then
  -- handle the error case
like image 127
Simon Wright Avatar answered Jul 28 '26 16:07

Simon Wright



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!