stringadabounded-types

What is the best way for initializing a fixed-length string in Ada?


I want to initialize a fixed-length String in Ada more or less like following:

S : String (1..256) := ("Hello", others => Character'Val (0));

I obtain an error while trying to compile. Is there any way to achieve something similar to the above?


Solution

  • The reason your code does not compile is that String is an array of Character so the equivalent would be

    s : String(1..256) := (1 => 'H',
                           2 => 'e',
                           3 => 'l',
                           4 => 'l',
                           5 => 'o',
                           others => Character'Val(0));
    

    Which is clearly far from ideal.

    Another way is to use the Move procedure in [Ada.Strings.Fixed][1].

    Move(Target => s,
         Source => "Hello",
         Pad => Character'Val(0));
    

    But this can't be done in the declaration.

    Finally, this compiles :

    s : String(1..256) := "Hello" & (6..256 => Character'Val(0));
    

    But I find it less clear [1]: http://www.ada-auth.org/standards/rm12_w_tc1/html/RM-A-4-3.html