samedi 14 décembre 2019

How to code the auto& in a if else or switch case format?

I used to have a code to extract certain part

auto& c = m_matrix[name];
....large block of code with using c in the calculation...

now I have to use a if/else or switch case for m_matrix options like the following statement:

switch input{
  case 1:
     auto& c = A[name];
  case 2:
     auto& c = B[name];
}
....large block of code with using c in the calculation...

A and B have the same type of elements. However, this is wrong as it will show that the definition of c is duplicated. At the same time, I can't declare auto& c; before switch/case as well like the following:

auto& c;
switch input {
   case 1:
      c = A[name];
   case 2:
      c = B[name];
}

....large block of code with using c in the calculation...

Is there a way to solve this problem?

Update: CinCout - Reinstate Monica kindly offers a solution of

switch input {
   case 1:{
      auto& c = A[name];
      ....large block of code with using c in the calculation...
   }
   case 2:{
      auto& c = B[name];
      ....large block of code with using c in the calculation...
   }
}

Is there a way to avoid the repetitive code in each case? Thanks

Aucun commentaire:

Enregistrer un commentaire