Shop OBEX P1 Docs P2 Docs Learn Events
Cog question — Parallax Forums

Cog question

Don MDon M Posts: 1,652
edited 2012-10-22 09:36 in Propeller 1
Why is a +1 added to a cognew statement such as this one from Full Duplex Serial?
okay := cog := cognew(@entry, @rx_head) + 1   

Comments

  • Mark_TMark_T Posts: 1,981
    edited 2012-10-22 09:25
    So that a valid cog number is logic true (ie non-zero). valid cog numbers are 0..7, add one and you can use 0 to represent no cog, 1..8 for cog numbers. So long as you subtract one again before calling cogstop in the Stop method
  • Don MDon M Posts: 1,652
    edited 2012-10-22 09:28
    Thanks Mark.
  • Duane DegnDuane Degn Posts: 10,588
    edited 2012-10-22 09:29
    If just a trick to make the returned value (of cog) zero so the parent object can use like below to see if a cog was successfully launched.
    returnVaule := childObj.Start
      if returnValue ' only a zero (cog not launched) will cause this not to be true
        ' do stuff if cog was successfully launched
      else
        ' do stuff if cog wasn't launched
    

    Otherwise the poor coder would have to type:
    returnVaule := childObj.Start
      if returnValue == -1
        ' do stuff if cog wasn't launched
      else
         ' do stuff if cog was successfully launched
    

    I personally don't like the practice of adding one to the cog value but I do it anyway so my objects can be used with the ones that do add one.

    I think one reason we have so many objects that add one is because Chip doesn't like to type and "if x" is easier to type than "if x == -1

    Edit: I think the perferred way to use this is:
    if childObj.Start
        ' do stuff if cog was launched
    
  • Mike GreenMike Green Posts: 23,101
    edited 2012-10-22 09:36
    Another reason to add one is that VAR variables in Spin are initialized to zero, so the initial value of a saved cog # means "no cog running". A lot of initialization methods for objects start by calling their stop method to make sure no cogs are already running. This won't work if you don't add one to the saved cog #. You'd need some other way to indicate that the object was never initialized (and to ignore the saved cog #).
Sign In or Register to comment.