3

I read somewhere that Ada allows a function only to return a single item. Since an array can hold multiple items does this mean that I can return the array as a whole or must I return only a single index of the array?

1
  • "A function can return a single item", but the item can be of any type, including array, record, task, protected type. What you read means that you can't declare a function that returns two objects, like function Func(x: Integer) return (String, Boolean); where you could say (N, B) := Func(3); I don't know of any strongly typed language that supports anything like that, but maybe some exist. Commented Oct 13, 2014 at 2:15

2 Answers 2

4

Yes, an Ada function can return an array - or a record.

There can be a knack to using it, though. For example, if you are assigning the return value to a variable, the variable must be exactly the right size to hold the array, and there are two common ways of achieving that.

1) Fixed size array - cleanest way is to define an array type, e.g.

type Vector is new Array(1..3) of Integer; function Unit_Vector return Vector; A : Vector; begin A := Unit_Vector; ... 

2) Unconstrained array variables.

These are arrays whose size is determined at runtime by the initial assignment to them. Subsequent assignments to them will fail unless the new value happens to have the same size as the old. The trick is to use a declare block - a new scope - so that each assignment to the unconstrained variable is its first assignment. For example:

for i in 1 .. last_file loop declare text : String := Read_File(Filename(i)); -- the size of "text" is determined by the file contents begin -- process the text here. for j in text'range loop if text(j) = '*' then ... end loop; end end loop; 

One warning : if the array size is tens of megabytes or more, it may not be successfully allocated on the stack. So if this construct raises Storage_Error exceptions, and you can't raise the stack size, you may need to use access types, heap allocation via "new" and deallocation as required.

Sign up to request clarification or add additional context in comments.

2 Comments

It may raise a Storage_Error, but that depends on what size of stack you are allowing your programs. - You are also missing a third option; allocating the needed memory on the heap.
Certainly, heap allocation is an option, as mentioned, but I was focussing on the common options and - at least in my work - it's not often I need to use it.
1

Yes, an Ada function can return an array. For example, an Ada String is "A one-dimensional array type whose component type is a character type." Several of the functions defined in Ada.Strings.Fixed—including Insert, Delete, Head, Tail and Trim—return a String.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.