From mboxrd@z Thu Jan 1 00:00:00 1970 X-Spam-Checker-Version: SpamAssassin 3.4.4 (2020-01-24) on polar.synack.me X-Spam-Level: X-Spam-Status: No, score=-1.9 required=5.0 tests=BAYES_00 autolearn=ham autolearn_force=no version=3.4.4 X-Google-Thread: 103376,d855403bbf39dab1 X-Google-NewGroupId: yes X-Google-Attributes: gida07f3367d7,domainid0,public,usenet X-Google-Language: ENGLISH,ASCII-7-bit Received: by 10.68.213.68 with SMTP id nq4mr7616622pbc.2.1328380596764; Sat, 04 Feb 2012 10:36:36 -0800 (PST) Path: lh20ni260377pbb.0!nntp.google.com!news2.google.com!news1.google.com!newsfeed2.dallas1.level3.net!news.level3.com!bloom-beacon.mit.edu!newsswitch.lcs.mit.edu!nntp.TheWorld.com!not-for-mail From: Robert A Duff Newsgroups: comp.lang.ada 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 Organization: The World Public Access UNIX, Brookline, MA Message-ID: References: NNTP-Posting-Host: shell01.theworld.com Mime-Version: 1.0 X-Trace: pcls6.std.com 1328380595 9371 192.74.137.71 (4 Feb 2012 18:36:35 GMT) X-Complaints-To: abuse@TheWorld.com NNTP-Posting-Date: Sat, 4 Feb 2012 18:36:35 +0000 (UTC) User-Agent: Gnus/5.1008 (Gnus v5.10.8) Emacs/21.3 (irix) Cancel-Lock: sha1:+1AW88NwNMxk8/6doMI/WWIwbjU= Content-Type: text/plain; charset=us-ascii Date: 2012-02-04T13:36:35-05:00 List-Id: "Nasser M. Abbasi" 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