Search code examples
if-statementvb6language-agnosticpseudocode

If statements not treated as boolean?


I'm a student, and my software teacher gave us this example -

BEGIN
IF first < second
    THEN display first,second
ELSE
    display second,first
ENDIF
END

If the two numbers, first and second were the same (say 2,2), the ELSE path would be taken, as first < second evaluates to false and so doesn't execute.

However, my software teacher said that in certain languages, both numbers being the same would be problematic and cause errors or strange behaviour (I believe he cited Visual Basic as an example). I do not see how this is possible. An IF statement is evaluated as either true or false and so one of the options MUST run and there should be no problem in evaluating whether 2 is less than 2.

Although he is my teacher and I respect him as such, I do not trust him completely and he does make errors at times. Is what he's said correct? And if so, could I have some specific examples of what happens? Thanks.


Solution

  • Perhaps he is talking (in a round about way) about floating point imprecision?

    there should be no problem in evaluating whether 2 is less than 2.

    This is not always the case for some numbers stored using an imprecise representation, for example:

    Dim first As Double, second As Double
    
     first = 0.3
    second = 0.1 + 0.2
    
    If first < second Then
        Debug.Print first, "is less than", second
    Else
        Debug.Print "equal or greater"
    End If
    

    Outputs:

    0.3 is less than 0.3

    See Is floating point math broken?

    This can manifest more visibly when one exceeds the safe bounds of a floating point type, for example in JavaScript:

    > 9007199254740992 == 9007199254740993
    < true