2

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.

Alex K.
  • 171,639
  • 30
  • 264
  • 288
GoatsWearHats
  • 272
  • 1
  • 9
  • 17

3 Answers3

4

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
Community
  • 1
  • 1
Alex K.
  • 171,639
  • 30
  • 264
  • 288
2

As far as I know, the expression in if (expression) always evaluates to a boolean. At least that is true in C, C++, PHP, Java, .NET, Python, Javascript...

But maybe it is not the case in some old or less-used languages.

For Visual Basic, this Microsoft documentation page clearly says that number < number will evaluate to FALSE.

Rosh Donniet
  • 418
  • 2
  • 10
0

Well clearly a < a is false, if a is Integer(not fractional number). However in case of fractional number this may be true of false. Let me give you instance of each for c language. C compiler uses IEEE-754 number representation for floating point.

take a=0.1273(stored in memory as:0.1272999423027039)

take b=0.12 and c=0.0073+b

now if you check, c It is true.