Question Beginner Question

rlbck38

New member
Joined
May 18, 2012
Messages
1
Programming Experience
Beginner
Help!!
Why does the following code result in -1 being displayed in the message box?

Dim abc, def, hij As Integer

def = 5
hij = 5

abc = def = hij

MessageBox.Show("The value of abc is " & abc)
 
This code:
VB.NET:
abc = def = hij
first tests whether 'def' is equal to 'hij', which evaluates to a Boolean value, i.e. either True or False and assigns the result to 'abc'. In this case the values are equal so the result is True. 'abc' is an Integer variable though, not a Boolean, so the value is implicitly converted to an Integer. In memory, the Boolean values True and False are stored as 32-bit numbers. True has all 32 bits set, i.e. 11111111111111111111111111111111, while False has all 32 bits cleared, i.e. 00000000000000000000000000000000. An Integer value that has all its bits set is equal to -1, so that's the value you get.

First up, please explain what you're actually trying to achieve and then we can explain how best to achieve it. It may be as simple as declaring 'abc' as type Boolean rather than Integer, but then again it might not. If you don't understand how that 32-bit value can be equal to -1 then you might start reading here:

Two's complement - Wikipedia, the free encyclopedia
 
First of all, Visual Basic does not permit chained assignments, as does the C programming language. Only the first = assignment operator is valid. The second = symbol is used to test equality of an expression, not to assign a value.

To reiterate and simplify what jmcilhinney said above:

The def = hij expression is assigned a value based on whether or not def is equal to hij. If it is equal, it is True. If it is not equal, it is False. Since you declared abc as an Integer, the True or False value is converted to either -1 (if True) or 0 (if False). That value (either -1 or 0) is then assigned to the variable abc.

Try changing the value of hij to another number. The messagebox will then return 0 instead of -1.

Also try changing the type declaration of abc to Boolean instead of Integer. It will then return either True or False.

If you simply want to assign the value of def to abc, then just leave out the second = hij
 
Last edited:
Back
Top