Variable assignment in if statements

Anything that doesn't fit elsewhere.
Post Reply
shinn
Posts: 2
Joined: Mon Aug 04, 2014 4:41 pm

Variable assignment in if statements

Post 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.
ted
Site Admin
Posts: 6289
Joined: Wed May 18, 2005 4:50 pm
Location: Yale University School of Medicine
Contact:

Re: Variable assignment in if statements

Post by ted »

What command line did you use to test your code?
shinn
Posts: 2
Joined: Mon Aug 04, 2014 4:41 pm

Re: Variable assignment in if statements

Post 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
ted
Site Admin
Posts: 6289
Joined: Wed May 18, 2005 4:50 pm
Location: Yale University School of Medicine
Contact:

Re: Variable assignment in if statements

Post 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
hines
Site Admin
Posts: 1682
Joined: Wed May 18, 2005 3:32 pm

Re: Variable assignment in if statements

Post 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
Post Reply