jtaseff Posted September 13, 2016 Share Posted September 13, 2016 Hi guys, I'm having an issue trying to make a conditional return. For example, I would like to do this: sub: doMath(&success) success = -1 //default is failure local math = 0; if (somethingbad==1) return; if (somethingelse == 1) return; math = 2+2; success = 1; //completed return; However, when I try to download this, the compiler can't deal with having multiple return statements. It doesn't recognize the "success" argument or the local variable "math" where they are needed after the conditional returns. This would be so much cleaner for us, instead of having to wrap multiple conditions into a huge if/else tree. Is there a way to get this to load properly? Happy IMTS! Link to comment Share on other sites More sharing options...
daves Posted September 14, 2016 Share Posted September 14, 2016 Hi I recreated this and agree it would be nice if it was made to work (or the script flow logic explained a bit more - there are other peculiarities which catch you out when switching between the C development and script, or the parser error message explaining what is wrong and how to fix...). Anyway, my first thought of a workaround with a global "return jump" seems to work and might be good enough? A little clunky: open plc 1 local suc; callsub sub.doMath(&suc); return; sub: doMath(&success) success = -1 //default is failure local math = 0; if (somethingbad==1) goto 9999 if (somethingelse == 1) goto 9999; math = 2+2; success = 1; //completed return; N9999: return; close or you could have a "return label" in each sub if that looks better, or this breaks other local variable scope... I haven't played with it too much. Link to comment Share on other sites More sharing options...
curtwilson Posted September 14, 2016 Share Posted September 14, 2016 The issue is in the pre-processor that is converting this to "raw" PPMAC code. It regards the first "return" statement as the end of this particular subroutine, and expects another "sub:" following it. PPMAC can take this structure in its raw code. The pre-processor will accept this syntax in a separate subprogram, because it understands that the subprogram extends until the "close" command. So this is another workaround. We are examining how to improve the pre-processor to allow this. Link to comment Share on other sites More sharing options...
DBMasterC Posted September 16, 2016 Share Posted September 16, 2016 My hacky solution involves abuse of the switch construct. While it adds some bloat, it does allow you to return early. Whether or not it's preferable to goto is in the eye of the beholder. sub: doMath(&success) switch(0) { case(0): success = -1 //default is failure local math = 0; if (somethingbad==1) break; //will exit the switch{}, hitting your return if (somethingelse == 1) break; math = 2+2; success = 1; //completed } return; Link to comment Share on other sites More sharing options...
Recommended Posts