Shop OBEX P1 Docs P2 Docs Learn Events
FB - DIM REGISTER vs VAR — Parallax Forums

FB - DIM REGISTER vs VAR

Which do I choose for local variables and why?

Craig

Comments

  • DIM REGISTER declares a global variable that lives in a register. This is generally a niche thing to do. The normal way to declare local variables is with just plain DIM or with VAR. The only difference is that VAR requires you to initialize the variable, and infers the type of the variable from the type of the expression. That is inside a function

    VAR x = "hello"
    

    is equivalent to

    DIM x AS STRING
    x = "hello"
    

    Outside of any functions they are slightly different, with VAR declaring a variable that's not accessible to subroutines and functions (i.e. that's "local" to the PROGRAM statements).

  • Thanks @ersmith Eric.

    I switched from a bunch of globals to VARs and the speedup was shocking :)

    What had me confused was that I got the impression that; whatever the VAR is initialized with, establishes its type.
    For example:

    Var a = 1

    A ubyte would suffice but I actually need a signed 32bit integer. Well, I actually do end-up with what I need so I guess that what the text really means is that:

    Var a = "1"

    Establishes the variable as a string

    Craig

  • @Mickster said:
    Thanks @ersmith Eric.

    I switched from a bunch of globals to VARs and the speedup was shocking :)

    What had me confused was that I got the impression that; whatever the VAR is initialized with, establishes its type.
    For example:

    Var a = 1

    A ubyte would suffice but I actually need a signed 32bit integer. Well, I actually do end-up with what I need so I guess that what the text really means is that:

    Var a = "1"

    Establishes the variable as a string

    Byte and word operations are slower and take up the same number of registers as long, so all integer expressions are treated as 32 bits for purposes of VAR. But there are more types than just string and integer, e.g.:

    VAR a = 1  ' a is an integer
    VAR a = 1.0 ' a is a single
    VAR a = [x : => x+1]  '  a is a function
    VAR a = b  ' makes a have the same type as b, *whatever* that is
    
  • @ersmith said:

    Byte and word operations are slower

    Ah, this I already expected to be the case but rather than appear lazy, was going to test.

    Thanks again.

    Craig

Sign In or Register to comment.