Home AMX User Forum AMXForums Archive Threads Tips and Tricks

Define_Function Variables

Spire_JeffSpire_Jeff Formerly Caffeinated ProgrammerPosts: 1,917
Not sure if this has changed or if I have just never run across this, but it seems that passing variables to a function is really just passing a reference to the main variable. This means that if you do any manipulation of the passed variable, it will change the value of the original variable. For example:
DEFINE_FUNCTION INTEGER CHECK_FOR_SOMETHING(INTEGER nSOMETHING)
{
STACK_VAR INTEGER nCNT;
WHILE (nSOMETHING >100)
{
  nSOMETHING = nSOMETHING -100
  nCNT++
}
RETURN nCNT;
}

.
.
.

nVAR = 205
nRESULT = CHECK_FOR_SOMETHING(nVAR)
SEND_STRING 0,"'nVAR = ',ITOA(nVAR),' and nRESULT = ',ITOA(nRESULT)'"
nRESULT = CHECK_FOR_SOMETHING(nVAR)
SEND_STRING 0,"'nVAR = ',ITOA(nVAR),' and nRESULT = ',ITOA(nRESULT)'"


The first string sent would be: nVAR = 5 and nRESULT = 2
The second string would be: nVAR = 5 and nRESULT = 0

I know this is a common concept in other programming languages, I just didn't recall ever encountering this in Netlinx (but it's possible I never performed ops on the variable passed). This is just a heads up to anyone that might have weird results coming from a function ;)

Jeff

Comments

  • NMarkRobertsNMarkRoberts Junior Member Posts: 455
    Arguments are passed by reference

    Try learning Ruby. When you assign the value of one variable to another, what you are actually doing is copying a reference to an object from one to the other. I get dizzy thinking about it.
  • DHawthorneDHawthorne Old Timer Posts: 4,584
    Even Axcess did this with the CALLs. You are passing a pointer to the original storage space. It's not unheard of in other languages, but it's not universal either. C++ makes a local copy of the parameters, you have to explicitly copy them over, or deliberately use a pointer variable to do the same thing. There are advantages to either way, but in the end, I prefer the C++ method. It took me quite a while to adjust to how Axcess and NetLinx handle parameters.
  • mpullinmpullin Obvious Troll Account, Marked for Deletion Posts: 949
    If you wanted to force Netlinx to leave the original value alone, couldn't you do something like CHECK_FOR_SOMETHING(nVAR+1-1) or even CHECK_FOR_SOMETHING(nVAR+0) ?

    Isn't that the same as passing the result of an expression like CHECK_FOR_SOMETHING(1+2)?
  • ipssheldonipssheldon Registered User Posts: 106
    If you don't want the value of what you pass in to affect the program, simply use a local variable inside the function, something like:

    DEFINE_FUNCTION INTEGER Check_For_Something(Integer nSomething)
    Local_Variable Integer nLocal,nCnt // Or use Local_Variable
    {
    nLocal = nSomething

    While (nLocal < 100)
    {
    nLocal = nLocal-100
    nCnt++
    }

    Return nCnt
    }
Sign In or Register to comment.