Treating Equations as Values
Reference > Science > Technology > Beginner Programming TipsA boolean variable is a variable which can hold one of two values. It can be True, or it can be False. Alternately, you could call the two values Yes andNo.
Using a boolean variable gives us another way toToggle A Value; we could use the following bit of code:
'Toggle A Boolean Variable
MyToggle = Not MyToggle
If the value was True, it becomes "Not True", orFalse. And if it was False, it becomes "Not False", orTrue.
So here's a question for you. Suppose you wanted to set MyToggle to True if X is equal to 7, but set it toFalse if X does not equal seven.
Here's one way to do it:
Dim X As Integer
'Set the boolean value
If X = 7 Then
MyBoolean = True
Else
MyBoolean = False
End If
That'll do the trick, but it's actually not the easiest way to do it. Because every equation can be treated as a Boolean value! You see, X either equals seven, or it doesn't equal seven. If X is not equal to seven, then the equation X = 7 is False.
Right?
So take a look at this:
Dim X As Integer
'Set the boolean value
MyBoolean = (X = 7)
To understand how this works, you should think of the second part of the equation (X = 7) as a question. The computer is asking: Is X equal to seven? And the answer to that question is either Yes(True) or No (False). So the entire line of code is really saying: Set MyBoolean to Yes if X equals seven, and No if X does not equal seven.
In other words, it's doing the same thing as the "If-Then-Else" statement shown above, but it's doing it with just one line of code instead of five!
You can get more complicated with this; take a look at the following code:
Dim MySecondBoolean As Boolean
Dim X As Integer
Dim Y as Integer
'Set the boolean values
MyFirstBoolean = (X = 7) Or (Y = 7)
MySecondBoolean = (X = 7) ANd (Y = 7)
This one sets the boolean value to True if either X equals seven or Y equals seven. The second one will only be True if both X and Y are equal to 7.