comp.lang.ada
 help / color / mirror / Atom feed
From: Robert A Duff <bobduff@shell01.TheWorld.com>
Subject: Re: can one create an array of a size determined by a constant value of a function?
Date: Sat, 04 Feb 2012 13:36:35 -0500
Date: 2012-02-04T13:36:35-05:00	[thread overview]
Message-ID: <wcclioiv424.fsf@shell01.TheWorld.com> (raw)
In-Reply-To: jgj33s$290$1@speranza.aioe.org

"Nasser M. Abbasi" <nma@12000.org> writes:

> I was looking at c++11 standard, where it show how
> one can allocate an array of some size. The size is
> determined by a function call. This is done at compile
> time though where the compiler can determine the result
> of the function, like this:
>
> http://en.wikipedia.org/wiki/C%2B%2B11#cite_note-2
>
> "constexpr int get_five() {return 5;}
> int some_value[get_five() + 7]; // Create an array of 12 integers. Legal C++11
> This allows the compiler to understand, and verify, that get_five is
> a compile-time constant.
> "

You can't declare that a function will return a compile-time-known
value.  But if the goal is efficiency, you don't need to -- the
compiler can figure it out.  For example, compile the program
below with "gcc -O2", and look at the generated assembly.
You'll see that Get_Five has vanished, and the array is allocated
just as if you had said "1..12" -- the expression "Get_Five+7" is
evaluated at compile time.

If Get_Five were separately compiled, you might need pragma
Inline.

If Get_Five returned something not known at compile time,
then the calculation would be done at run time, and a dynamic
array would be allocated on the stack.

with Text_IO; use Text_IO;
procedure Main is

   function Get_Five return Integer;
   function Get_Five return Integer is
   begin
      return 5;
   end Get_Five;

   Some_Value: array (Integer range 1 .. Get_Five + 7) of Integer;

begin
   for X in Some_Value'Range loop
      Some_Value(X) := X;
   end loop;

   Put_Line(Some_Value(12)'Img);
end Main;

- Bob



  parent reply	other threads:[~2012-02-04 18:36 UTC|newest]

Thread overview: 5+ messages / expand[flat|nested]  mbox.gz  Atom feed  top
2012-02-04 11:00 can one create an array of a size determined by a constant value of a function? Nasser M. Abbasi
2012-02-04 12:03 ` Yannick Duchêne (Hibou57)
2012-02-04 18:36 ` Robert A Duff [this message]
2012-02-04 18:47 ` Jeffrey Carter
2012-02-05 11:12 ` Pascal Obry
replies disabled

This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox