Define constant integer with if condition in c++

To use a constant integer with the if condition I am using this logic in c++ code which compile with the g++ but not with root compiler.

#include <iostream>
using namespace std;

int main() {
     int wafer = 26;
    int nof1;

    if (wafer == 26)
    {
        nof1 = 25;
    }
    if (wafer == 10)
    {
        nof1 = 40;
    }
     const int nof = nof1;

     int array[nof] = {0};
     return 0;
}

In the root compilation I am getting this error, /home/sawan/FoCal_India/position_scan_pi/check.cxx:18:16: error: variable-sized object may not be initialized
int array[nof] = {0};
^~~

may be:

   int array[nof];
   for (int i=0; i<nof; i++) array[i] = 0;

Hi,

instead of

int array[nof] = {0};

do

int array[nof];
memset(array, 0, sizeof(array));

I have many arrays, histograms and graphs in to code whose size will be given by nof. So does this method works for histograms also? Like TH1F *histograms[nof];

You mean you have arrays of histograms and arrays of graphs? Why would you need to nullify the elements of such arrays?

You do not need to initialize the array to 0. Example:

void sawan() {
   int wafer = 26;
   int nof1;

   if (wafer == 26) nof1 = 25;
   if (wafer == 10) nof1 = 40;

   const int nof = nof1;

   int array[nof];
   memset(array, 0, sizeof(array));

   TH1F *histograms[nof];

   auto c = new TCanvas("c","c",1000,1000);
   c->Divide(5,5);
   for (int i=1; i<=nof; i++) {
      histograms[i-1] = new TH1F(Form("h%d",i),Form("h%d",i),100, -4,4);
      histograms[i-1]->FillRandom("gaus",20000);
      c->cd(i);
      histograms[i-1]->Draw();
   }
}
1 Like

What about std::array?

#include <array>

void f()
{
    constexpr int a = 20;
    constexpr int b = (a == 20 ? 30 : 40);

    std::array<int, b> ar;
    ar.fill(0);
}
1 Like

For arrays, I am only filling the array at certain position and rest of the position I need to fill it with zero. This is why I was initializing them with 0;