Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does "If a < b < c Then" actually do in vb.net?

Here is some "bad" code:

Module test
    Sub Main()
        Console.WriteLine("1<2 =   " + cstr((1<2)))
        Console.WriteLine("2<1 =   " + cstr((2<1)))
        Console.WriteLine("1<2<3 = " + cstr((1<2<3)))
        Console.WriteLine("3<2<1 = " + cstr((3<2<1)))
    End Sub
End Module

The output from this is:

1<2 =   True
2<1 =   False
1<2<3 = True
3<2<1 = True

1<2<3 is True, but not for the right reasons.

3<2<1 evaluates to True as well. Why?

Can someone explain what's going on here?

I know I should be using a<b and b<c but I want to know what happens when you use consecutive operators. ie, why doesn't the compiler cry!! Is syntax like this used for something else?

like image 788
jon Avatar asked Jan 17 '26 04:01

jon


2 Answers

It evaluates it left to right, so 3<2<1 is the same as (3<2)<1. Because expression in parentheses is false, the whole thing evaluates to 0<1 which is true.

like image 90
Phonon Avatar answered Jan 19 '26 20:01

Phonon


First of all, with Option Strict On, the compiler does cry. With Option Strict Off, here's what happens:

  • 3 < 2 < 1 is evaluated from left to right, so it's the equivalent to (3 < 2) < 1
  • 3 < 2 is evaluated to False so the compiler evaluates: False < 1
  • VB converts boolean value False to 0, so that it can be compared with another int value
  • 0 < 1 is evaluated to True
like image 26
Meta-Knight Avatar answered Jan 19 '26 20:01

Meta-Knight



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!