Shop OBEX P1 Docs P2 Docs Learn Events
Explain the use of the word constant in a line of code — Parallax Forums

Explain the use of the word constant in a line of code

Don MDon M Posts: 1,653
edited 2011-06-27 17:51 in Propeller 1
What is the difference between this:

i2c.ReadLong(i2c#BOOTPIN, EE_DEVICE_ADDR, constant(EE_BASE_ADDR + $0))

and this:

i2c.ReadLong(i2c#BOOTPIN, EE_DEVICE_ADDR, EE_BASE_ADDR)

What does "constant" do along with the "+ $0" ?

BTW I did read the Propeller manual pages 91 & 92 but I don't quite understand it.

Thanks.
Don

Comments

  • Jay B. HarlowJay B. Harlow Posts: 79
    edited 2011-06-27 15:13
    In your example there is no difference at run time; due to adding $0.

    When it makes a difference is if you add a number other then $0.

    For example, assume EE_BASE_ADDR has a value of $1000:
    i2c.ReadLong(i2c#BOOTPIN, EE_DEVICE_ADDR, constant(EE_BASE_ADDR + $4))
    

    Will do the addition EE_BASE_ADDR + $4 at compile time passing $1004 at run time.

    While
    i2c.ReadLong(i2c#BOOTPIN, EE_DEVICE_ADDR, EE_BASE_ADDR + $4)
    

    Will do the addition at runtime (on the propeller). In other words the second one will be slightly larger and slightly slower.

    Hope this helps
    Jay
  • potatoheadpotatohead Posts: 10,261
    edited 2011-06-27 15:24
    The nice thing about constants is they can be changed as a group. At compile time, the value of the constant is placed into the code for use at run-time, just like typing a value in the code yourself does. Where there are lots of similar values, or perhaps values that are related in some way, having them expressed as constants gives you one central location to make changes to those values without fear of forgetting one, or mis-calculating one.
  • Dave HeinDave Hein Posts: 6,347
    edited 2011-06-27 15:56
    In your example there is no difference at run time; due to adding $0.
    The Prop tool will generate code to add the zero. Even BST will generate code to add zero. There is an option in BST to fold constant expressions into a single constant, but with this option enabled it will still add the constant even if it has a value of zero.
  • Don MDon M Posts: 1,653
    edited 2011-06-27 17:51
    Gentlemen- thanks for the explanation.
Sign In or Register to comment.