0

Im having a little problem with my code. here i called a function to make a test, if it passed it goes back and continue if it doesn't it goes to main loop.

void loop()
{

    if (call == 1)
    {
        funca(); 
    }
    print("waiting..");
}
 void funca() 
    {
        gsmtest();
        print("calling..")   
    }
 void gsmtest() 
    {
        if (test==1)
             {
            print("test ok");
             } 
        else
              {
                print("error");
                loop();
              }
    }

here is a simple example, if u press call, the code goes to funca which make a call to gsmtest. if test goes ok it print "calling.." if not it print "error" and goes back to loop. for some reasons here if test failed, it print error and than goes to loop after that it print "calling.." (continuing funca which i want to abort it if test goes wrong) .

1 Answer 1

1

You're overflowing your stack due to infinite recursion.

By explicitly calling loop() you are breaking the whole call stack system. You effectively have:

loop() ->
  funca() ->
    gsmtest() ->
      loop() ->
        funca() ->
          gsmtest() ->
            etc...

Instead of>

loop() ->
    funca() ->
        gsmtest()
    <-
<-

Instead of calling loop() you should use return; to "return" back to where the function was called from.

For example:

void loop() {
    if (call == 1) {
        funca();
    }    
    print("waiting..");
}

void funca() {
    if (!gsmtest()) return;
    print("calling..")
}

bool gsmtest() {
    if (test == 1) {
        print("test ok");
    } else {
        print("error");
        return false;
    }
    return true;
}
4
  • but in that case if gsmtest is error it will continue to the next instruction (it will print "calling.." while it doesn't suppose to).
    – Med. A.
    Commented Feb 18, 2017 at 19:44
  • So you have it returning a value that says "this failed" then test for that in the calling function, then return from that too.
    – Majenko
    Commented Feb 18, 2017 at 19:44
  • yes its my back up plan, but i'm looking for better way, without using variables.
    – Med. A.
    Commented Feb 18, 2017 at 19:47
  • 1
    You won't find a better way. This is how it is done. And you don't need variables. Let me craft an example for you.
    – Majenko
    Commented Feb 18, 2017 at 19:48

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.