john c. j.
john c. j.

Reputation: 1175

Undefined variables in `if` statement

This will work as expected:

a := "111"
b := "222"

if (a != "aaa" and b != "bbb")
    MsgBox, Yes

But the "Yes" message will be also shown if one of the variables is not defined

; a := "111" ; Commented line
b := "222"

if (a != "aaa" and b != "bbb")
    MsgBox, Yes ; Since var "a" is not defined, I don't want this message box

Here is how I fix it:

; a := "111"
b := "222"

if ((a and b) and (a != "aaa" and b != "bbb"))
    MsgBox, Yes

But from my point of view it looks like something awful. Is there exist more correct way?

Upvotes: 0

Views: 272

Answers (1)

Jim U
Jim U

Reputation: 3366

Since and is commutative, you can do without the parentheses:

if a and b and a != "aaa" and b != "bbb"

ALTERNATIVE SOLUTION

Initialize your variables to the value you're testing (aaa) so that if your implementation code doesn't alter them, you'll get the desired result:

a=aaa
b=bbb

... do some stuff ...

global a,b
if a != "aaa" and b != "bbb"
    MsgBox, Yes

EXPLANATION

When a is undefined, it seems like you want undefined != "aaa" to somehow evaluate to false. That's the same as saying you you want undefined == "aaa" to somehow evaluate to true. Your logic is too complex for that.

Here's a state table for your logic:

                Actual  Desired T1      T2
a       b       MsgBox  MsgBox  a!=aaa  b!=bbb  T1 and T2
-----   ------  ------  ------- ------  ------  -----
undef   undef   Yes     no      true    true    true 
undef   bbb     no      no      true    false   false
undef   222     Yes     no      true    true    true    The example you didn't want
aaa     undef   no      no      false   true    false  
aaa     bbb     no      no      false   false   false
aaa     222     no      no      false   true    false
111     undef   Yes     no      true    true    true
111     bbb     no      no      true    false   false
111     222     Yes     Yes     true    true    true    Only one you want

The Actual MsgBox column shows when the message box appears in your original code. Desired MsgBox=Yes is what you wanted to happen. T1 and T2 are the partial calculations of your condition. T1 and T2 is the final value of your condition.

The last row shows the only state in which you want the MsgBox to appear; when a is equal to niether aaa nor undefined AND b is equal to neither bbb nor undefined.

So we can simplify the logic by initializing a to "aaa" and b to "bbb". In effect we are combining your the two conditions for each variable into a single condition by making the two values ("aaa" and undefined) equivalent.

I hope that makes sense

Upvotes: 1

Related Questions