Arrays with variable size in macros


I need to use arrays with variable size in a macro. I do something like

int const A=6;
int const B=10;

for(int a=0 ; a<A ; a++)
for(int b=0 ; b<B ; b++)

.....(a code that computes the number of bin nbbin).....

int const C = nbbin;

double value[C];

for(int c=0 ; c<C ; c++)
value[c] = c+1;

What I don;t understand, is that even though value[C] is being redefined in the loops over A and B, its size seems to be constant. Eg I get

–first iteration on B
C = 34
–second iteration on B
C = 63
Error: Array index our of range value -> [34] valid upto value[33]

What am I doing wrong?


If I don’t say a stupid thing, if you say:

int const C="whatsoever";

It will remain “whatsoever” until you close the program.
Try to remove the adjective “const” …

Tayash uses const because the array index should be const. But he doesn’t want it to be const because he wants to change it. You should probably use a std::vector instead.

I really don’t understand!
Sorry for my ignorance, but the assertion that an array wants a const
index is a request of c++ or root package?
I tell you this because sometimes I think that I use root in a naive mode
so if I could understand it in a better way I will be happy.
(and also a better programmer)


Hi Paolo,

[quote=“paolomarco”]but the assertion that an array wants a const
index is a request of c++ or root package?[/quote]
The C++ standard (at 8.3.4) requires the array size to be an integral constant expression and ROOT (CINT, actually) follows that rule.


Hello ROOTers,

Thanks for your replies. Indeed using a vector solved that problem, but now I am facing another one. I now want to use the values I store in value as the x-values of points in a TGraphError - but TGraphError wants an array, which in turn cannot be defined with a variable size by C++ standard rules, so I’m stuck in a vicious circle :frowning:
What would you recommend?

Thanks again for your help and kindness.

I hope I get your question right:
when you have a vector:
vector v;
and you have a function which wants a pointer to the array, you can use a reference to the first element of the vector: &v[0] as a pointer to your vector.

vector is a standard container :wink:

P.S. sorry if I misunderstood your question

Thanks anar!

You are welcome :slight_smile:

BTW, here we have the reference for the method above (from ISO 14882, 2nd ed., 23.2.4 [lib.vector])