Page 1 of 1

Variable assignment in if statements

Posted: Tue Aug 05, 2014 9:23 am
by shinn
Hello,

I have encountered some unexpected behavior when assigning a variable in an if statement. Consider the following minimal working example, which checks to see if a variable was passed via a -c command line argument:

Code: Select all

print name_declared("myparam")
if (name_declared("myparam")!=5) {
    print "Case 1"
    myparam = 3
} else {
    print "Case 2"
}
I receive the following unexpected output:

Code: Select all

0 
Case 2
However, when I comment out the assignment within the if statement, I see the expected output:

Code: Select all

0 
Case 1
I saw the post here and am currently using the workaround of passing a substitute variable name as is done here, but thought I should report the bug regardless in case it is unknown. I saw nothing in the documentation on the subject and could not find a bugtracker.

I am running NEURON "VERSION 7.3 ansi (1078:2b0c984183df) 2014-04-04", compiled from source using the "--with-nrnpython" and "--paranrn" compiler flags on GNU/Linux x86_64, 3.2.0-29-generic.

Re: Variable assignment in if statements

Posted: Tue Aug 05, 2014 10:42 am
by ted
What command line did you use to test your code?

Re: Variable assignment in if statements

Posted: Tue Aug 05, 2014 12:00 pm
by shinn
I used the typical "nrniv mwe.hoc". Running "nrniv -c "myparam=10" mwe.hoc" gives the expected result of

Code: Select all

5 
Case 2

Re: Variable assignment in if statements

Posted: Tue Aug 05, 2014 1:20 pm
by ted
Here is a workaround for now:

Code: Select all

result = name_declared("myparam")
if (result!=5) {
    print "Case 1"
    myparam = 3
} else {
    print "Case 2"
}
print "myparam has the value ", myparam

Re: Variable assignment in if statements

Posted: Wed Aug 06, 2014 2:37 pm
by hines
I think there is kind of a chicken and egg problem here. When you are checking in the 'name_declared' function, the name exists because it has been
mentioned inside the if block (looked at during parsing). One can avoid this with the idiom
execute("myparam = 3")
inside the if block.

As an example of this, I often use for param.hoc files:
https://senselab.med.yale.edu/modeldb/s ... \param.hoc