0

I'm building a 16 state FSM on a PIC18 with C18. I'm considering having each state as its own function which jumps to and gets jumped by other states. I'm tempted to just write a branch cases of "state##();"s at the end of each state to determine where the program should go, but I'm thinking this would die pretty quickly since the compiler likely expects this to return, not branch forever; the stack on my microcontroller would quickly fill up and eventually overflow.

Is C18 smart enough to know that my function call will never return back and replace the instruction with a GOTO/JMP instead of a CALL/BRANCH accordingly? I'm aware GOTO exists in C (and is usually strongly advised against for readability reasons) but I can't think of more appropriate reason to use it than here. I'm aware that I can just force it to goto with an _asm _endasm block, but I'll save myself the trouble if it's not necessary. What would be the best way in C to say to go to a function and never come back?

Naturally, all help is appreciated

BB ON
  • 251
  • 1
  • 3
  • 15
  • 2
    There is no generic answer to such a question, some compilers will others wouldn't. Usually compilers have a commandline option to produce the assembler instead of the object code. (e.g for gcc this is `-S`). Inspect that assembler and you will know. Modern C aka C11 even has a keyword that lets you specify that: `_Noreturn`. – Jens Gustedt Mar 08 '13 at 18:09
  • The best way IMO is to not worry about it. What are you looking to save? Memory usage would be only a trivial optimization. – kenny Mar 08 '13 at 18:26
  • I'm pretty sure I have to worry about it. If the compiler uses "call" then it keeps saving the program counter when I travel along the fsm and never returns. Goto doesn't save the program counter on the stack so I don't have to worry about overflows. – BB ON Mar 08 '13 at 19:13

1 Answers1

2

It seems like what you're talking about would be some sort of recursive design which is the only way that function calls would keep stacking up. I don't think you have the right idea for how a state machine works. Try taking a look at this for a great template for FSM in C:

C state-machine design

If you wanted to post some of your sample code or how you were thinking about implementing it we could help more.

Community
  • 1
  • 1
ThePosey
  • 2,734
  • 2
  • 19
  • 20
  • Yeah, putting each state as a function wasn't the best way of thinking about it. A while loop and a case switch is a lot easier. Thanks – BB ON Mar 08 '13 at 23:42