adaunchecked-conversion

Suppress warnings for unchecked conversion


I have this piece of code :

with Ada.Unchecked
private package MyPackage is
    function UC_Bool_To_U8 is new Ada.Unchecked_Conversion (Source => Boolean, Target => T_U8);
end MyPackage;

Where T_U8 is :

type T_U8 is range 0 .. 2**7;

Function UC_Bool_To_U8 is working but I have warnings on compilation :

warning: types for unchecked conversion have different sizes

warning: size of "Boolean" is 1, size of "T_U8" is 8

warning: source will be extended with 7 high order zero bits

How can I suppress theses warnings ?


Solution

  • Warnings can be suppressed by using a pragma as shown in this Ada Gem blog post and the following example:

    main.adb

    with Ada.Unchecked_Conversion;
    
    procedure Main is
    
       --  Using a modular type instead of an integer type. Result is the same.
       type T_U8 is mod 2**7;    
       
       pragma Warnings (Off, "types for unchecked conversion have different sizes");   
       
       function UC_Bool_To_U8 is new Ada.Unchecked_Conversion
         (Source => Boolean, Target => T_U8);
       
       pragma Warnings (On, "types for unchecked conversion have different sizes");
       
    begin
       null;
    end Main;
    

    However, please also consider to not use Unchecked_Conversion when converting a boolean type to some integer or modular type. The compiler will completely optimize away a simple if-statement as can be seen in the Compiler Explorer:

    input to Compiler Explorer

    pragma Source_File_Name (To_U8, Body_File_Name => "example.adb");
    
    with Interfaces.C.Extensions;
    
    function To_U8 (B : Boolean) return Interfaces.C.Extensions.Unsigned_8 with Inline is
    begin
        return (if B then 1 else 0);
    end To_U8;
    

    ouput of Compiler Explorer (using compiler switch -O1 or -O2)

    _ada_to_u8:
            mov     eax, edi  # b, tmp86
            ret