|
[Sponsors] |
March 7, 2011, 10:46 |
Variable Declaration And Initialization
|
#1 |
New Member
Join Date: Jan 2011
Posts: 4
Rep Power: 15 |
Hello everybody!
I try to read two files only if a certain condition is met. Unfortunatelly I don't know how to separately declare and initialize a volScalarField and a dimensionedScalar. My first approach did not work, because after the end of the if-conditions both variables "C" and "DC" are lost: Code:
if (condition) { volScalarField C ( IOobject ( "C", runTime.timeName(), mesh, IOobject::MUST_READ, IOobject::AUTO_WRITE ), mesh ); // read the transportProperties file IOdictionary transportProperties ( IOobject ( "transportProperties", runTime.constant(), mesh, IOobject::MUST_READ, IOobject::NO_WRITE ) ); // diffusion coefficient for the passive scalar dimensionedScalar& DC ( transportProperties.lookup("DC") ); } Thanks a lot for your help! Regards Martin |
|
March 7, 2011, 12:46 |
|
#2 |
Member
Ivor Clifford
Join Date: Mar 2009
Location: Switzerland
Posts: 94
Rep Power: 17 |
This is a C++ issue. Strictly speaking you can't optionally declare a variable. What you can do, however, is declare a pointer (or autoPtr) to the volScalarField, initialize it as NULL, and optionally set the pointer in the if-condition. Using autoPtr is the safest option since the object will automatically destruct at the end of your program.
For the dimensionedScalar I'd just declare it anyway since it uses up so little memory and use a bool to check it it has been set afterwards. Code:
autoPtr<volScalarField> C; dimensionedScalar DC("DC", dimless, 0); if (condition) { C.set(new volScalarField ( IOobject ( "C", runTime.timeName(), mesh, IOobject::MUST_READ, IOobject::AUTO_WRITE ), mesh )); DC = dimensionedScalar(transportProperties.lookup("DC")); } Last edited by cliffoi; March 7, 2011 at 12:51. Reason: Bad formatting of source code |
|
March 8, 2011, 11:42 |
|
#3 |
New Member
Join Date: Jan 2011
Posts: 4
Rep Power: 15 |
Thank you cliffoi for your help! It works now
|
|
|
|