Re: [ROOT] Adjustable array dimension

From: Radovan CHYTRACEK (Radovan.Chytracek@cern.ch)
Date: Thu Mar 08 2001 - 17:47:51 MET


Victor Perevoztchikov wrote:
> 
> Hi Radovan,
> 
> > > Int_t fun(const Int_t n, Int_t x) {
> > >    Int_t arr[n];
> 
> such array is forbidden by C++. Even if CINT can handle
> it, it is better to avoid non C++ constructions

Hi,

           I know, but G++ can handle it as well, look:

test.C
-----------------------------------------------------------------------------
#include <iostream>

typedef int Int_t;

 Int_t okfun(const Int_t n, Int_t x) {
    Int_t* arr = new Int_t[n];
    arr[n-1] = x;
    Int_t ret = arr[n-1];
    delete [] arr;
    return ret;
 }
 
 void okpass(Int_t k, Int_t x) {
    for (Int_t i=1; i<=k ; i++)
       cout << "okfun(" <<i<<","<<x<<") = " << okfun(i,x) << endl;
 }
 
 Int_t fun(const Int_t n, Int_t x) {
    Int_t arr[n];
    arr[n-1] = x;
    return arr[n-1];
 }

 void pass(Int_t k, Int_t x) {
    for (Int_t i=1; i<=k ; i++)
       cout << "fun(" <<i<<","<<x<<") = " << fun(i,x) << endl;
 }

int main( int argc, char* argv[] )
{
 cout << fun(1,5) << endl;
 cout << fun(2,5) << endl;
 pass(2,5);
 cout << okfun(1,5) << endl;
 cout << okfun(2,5) << endl;
 okpass(2,5);
 return 0;
}

-----------------------------------------------------------------------------
% g++ -g -Wall -ansi test.C -o test.exe
% ./test.exe 
5
5
fun(1,5) = 5
fun(2,5) = 5
5
5
okfun(1,5) = 5
okfun(2,5) = 5

Radovan




This archive was generated by hypermail 2b29 : Tue Jan 01 2002 - 17:50:39 MET