Shop OBEX P1 Docs P2 Docs Learn Events
Yet another SPIN minutia question: assignment operator (and truncation) — Parallax Forums

Yet another SPIN minutia question: assignment operator (and truncation)

agsags Posts: 386
edited 2013-05-12 15:05 in Propeller 1
In another thread (see here: http://forums.parallax.com/showthread.php/147876-At-wit-s-end-A-call-for-(debugging)-suggestions?p=1183045&viewfull=1#post1183045) I made an incorrect statement, claiming that the locknew example in the Propeller Manual was incorrect. Testing proved me wrong.

Distilling that down to a minimal example, why does this work when a lock is not available?:
VAR
  byte lock
PUB GetLock
  if (lock:=locknew) == -1
    'no lock is available, take some other action here
    return -1
  else
    return lock 'successfully reserved a lock
Before I knew enough to make incorrect statements, this looked perfectly reasonable to me. Then I learned more and became dangerous. I learned that assigning a long or word to a byte (or a long to a word) truncated the assigned value. I also learned that when a byte or word was assigned to a long (or a byte assigned to a word) there is no automatic sign extension. So clearly, assigning the value -1 to lock resulted in lock containing the value 255. 255 is never equal to -1. So just why does this work?

I suppose I am assuming the value of an assignment operator is the value of the LHS symbol. It appears that the value of an assignment operator is an intermediate value, equal to the evaluated RHS. Is that close to the reason why this works?

Comments

  • Mike GreenMike Green Posts: 23,101
    edited 2013-05-12 15:05
    There's a variant of the assignment operator that leaves the value on the stack rather than popping it. That's what's used in the example you gave and that's why you can test for -1 even though the value is truncated when stored in a byte. In some other languages, the value of an assignment is indeed the LHS value. In Spin, it's the RHS expression which is always a 32-bit value. Byte and word values are unsigned and converted to 32-bit positive values.
Sign In or Register to comment.