Strange behaviour of FE initialization in a loop

Dear all,

I am trying to understand the strange behaviour of the small example:

mesh Th = square(1,1); 

macro def(i)[i, i#B]// EOM          // vector field definition
func Pk = [P1, P1]; 

fespace Wh0(Th, Pk); 
Wh0 def(u);

for (int i=0; i< 5; i++){ 

    cout << " FIRST COUT " << endl; 
    cout << u[] << endl; 

    fespace Wh(Th, Pk);
    Wh def(u);
    u[] = 1e-3; 

    cout << " SECOND COUT " << endl; 
    cout << u[] << endl; 
}

For each iteration I get

FIRST COUT
8
0 0 0 0 0
0 0 0
SECOND COUT
8
0.001 0.001 0.001 0.001 0.001
0.001 0.001 0.001

So, why the first cout is always 0, whereas u[] is re-initialize only after the first cout ?

Would someone have an explanation about this observation ?

Thank you in advance,

Best regards,

Loïc,

You are couting uninitialized memory. There is no guarantee that it will always be 0.

So if I understand well the first u[] is not equal to 1e-3 after the first iteration. The two u[] are different objects and the first one continue being an object of Wh0.

But for example, if I do something as:

fespace Wh0(Th, Pk); 
Wh0 def(u0);


for (int i=0; i< 5; i++){

* varf with u0 on the RHS

fespace Whnew(Th, Pk);
Whnew def(u);

* Find u by solving varf
* Th = movemesh(Th, ...)
* u0[] = u[]
}

My problem is there. I want to define a new u0 living in Whnew, but the u0 that I have used in the varf remains the first u0 that I have defined outside the loop.

How to initialize properly my u0 , so that I can redefine it at each iteration ?

Best regards,

Loïc,

Please use an actual code. Your first snippet is perfectly functioning, and I don’t see what the issue is here. There are multiple such examples for mesh adaptation.

The fact is that when you declare a variable inside a subsection delimited by braces {}, it is a local definition only valid within these braces. When you leave these braces, in your case the name “u” recovers its declaration and values that were valid before the {} (here no value was given thus it gives 0).
Here you have a loop thus for each value of i you open and close a new subsection {}.
If you want to keep the value that you compute inside the {}, you must save it in a variable that was declared outside the {}. I think that it is not possible to declare a global variable inside a {}.

But as Pierre says, it works in the context of movemesh: you change Th within the loop, but make no declaration within the loop (in particular you do not declare fespace Whnew(Th, Pk);). Only the unknowns are updated. The unknowns are declared outside the loop.

Thanks, I have understand now.
I was misinterpreting the {} for the for loop and the declaration of fespace.

Best regards,

Loïc