-Wmaybe-uninitialized warning

G4VSolid* wlsSolid;
  if(pVol == NULL){

    if(fShape == "square"){
      G4VSolid* innerSolid = new G4Box("innerSolid",length_inner,length_inner,fLength);
      G4VSolid* outerSolid = new G4Box("OuterSolid",length_outer,length_outer,fLength);
      wlsSolid = new G4SubtractionSolid("wlsSolid",outerSolid,innerSolid);
    }
    else if(fShape == "circle"){
      wlsSolid = new G4Tubs("wlsSolid",length_inner,length_outer,fLength,0,2*pi);      
    }
    else
      MGLog(error) << "Incorrect shape for fiber core : "<<fShape<<" not valid! \n use square or cirlce"<<endlog;

    pVol = new G4LogicalVolume(wlsSolid,G4Material::GetMaterial(this->GetMaterial()),logicalName); 
  }

This is my code snippet. When I try to compile the code, it compiles fine but it returns a warning

warning: ‘wlsSolid’ may be used uninitialized in this function [-Wmaybe-uninitialized]
pVol = new G4LogicalVolume(wlsSolid,G4Material::GetMaterial(this->GetMaterial()),logicalName);

I would really like to remove these warnings as there are other classes with similar code and they, too, return a warning like this.
One way I found out was to modify the snippet as follows:

  if(pVol == NULL){

    if(fShape == "square"){
      G4VSolid* innerSolid = new G4Box("innerSolid",length_inner,length_inner,fLength);
      G4VSolid* outerSolid = new G4Box("OuterSolid",length_outer,length_outer,fLength);
      G4VSolid wlsSolid = new G4SubtractionSolid("wlsSolid",outerSolid,innerSolid);
      pVol = new G4LogicalVolume(wlsSolid,G4Material::GetMaterial(this->GetMaterial()),logicalName); 
    }
    else if(fShape == "circle"){
      G4VSolid wlsSolid = new G4Tubs("wlsSolid",length_inner,length_outer,fLength,0,2*pi);
      pVol = new G4LogicalVolume(wlsSolid,G4Material::GetMaterial(this->GetMaterial()),logicalName); 
    }
    else
      MGLog(error) << "Incorrect shape for fiber core : "<<fShape<<" not valid! \n use square or cirlce"<<endlog;
  }

Is there another(read : better/smarter) way to do it?

I think the modified way is pretty clear - it’s an error to pass a nullptr as the G4VSolid argument to G4LogicalVolume's constructor, so this guarantees that’s not the case. In the original code, all I think is needed is to modify the first line to:

G4VSolid* wlsSolid = nullptr;

to remove the warning. However, unless the MGLog(error) statement is going to return/exit/throw at this point, the last line constructing pVol is still going to run with a bad value of the wlsSolid pointer.

Thank you! That helps and it is a neater solution.

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.