Range based looping and C++ funkiness...

I created this in CLion just now (it’s the FOR Loop in the SETUP switch case that I wish to discuss):

void p4() {
    static int mode = SETUP;
    static int profile = 0;
    static unsigned long* p[5];
    switch (mode)
    {
 case RUN:
 recordResponse(motor.doMotorProfile(p[profile++]));
 profile = (profile > 5) ? 0 : profile;
 break;
       
 case SETUP:
 for (int x=0; x < 5; x++)
 {
 unsigned long ap[5] = {millis(),BOTH,getTime(x),getAngle(x),x};
 p[x] = ap;
 }
 mode = RUN;
 break;
 }
}

Then CLion highlighted the word ‘For’ so I hovered on it and it said that I should use a range-based loop instead and asked me if it would like me to allow it to go ahead and re-structure that loop for me …

I thought for a minute “RANGE based loop? what new magic is this?” So I said “Sure, have at it!” … and it did … but what it did to my loop … kinda makes sense to me … so I googled around for range-based loops and the explanations CONCEPTUALLY make sense to me, but I think I’m stuck on the structure and what’s actually happening in this specific case.

for (auto & x : p)
{
    unsigned long ap[5] = {millis(),BOTH,getTime(x),getEngle(x),x};
    x = ap;
}

It looks like it moved the array I was assigning new arrays into … up to the top line but then remove the index reference and stuck it on the lower line? But then it set that index equal to the array that I’m assigning to that index … maybe??? And then it tossed an ampersand in there … I assume that wasn’t for comic relief … and thankfully it left my array constructor alone but it made spaghetti out of everything else…

And how would someone look at that and know which values it’s going to use for x?

Would someone be able to break this down for me? I would appreciate any comments that might help me make better sense of this.

I mostly write in Java so C tends to be a little … ‘mechanically rigid’ for me … so try not to be annoyed with my questions and inability to comprehend, if you would please?

Thank you,

Mike

I had to look up cLion to see that it is a c/c++ IDE.

Anyway, you cannot define a variable in a local context (automatic variable) and keep a pointer to it outside that context.
Concretely, you have defined a 5 element array ap in an iteration of a for loop, and are attempting to keep a pointer to it in another array p. The storage for ap is released at the end of the loop iteration so the pointers is invalid.

I’ve still got to understand how cLion attempted to interpret your code.

6v6gt:
I had to look up cLion to see that it is a c/c++ IDE.

And a damn good one ... Jetbrains makes the best IDEs I've ever seen.

6v6gt:
I’ve still got to understand how cLion attempted to interpret your code.

Thank you, that actually makes me feel better. :slight_smile: