Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does my "if" statement appear not to run?

I'm defecting from C# to Delphi 2009, I'm liking it so far very much.

I wrote a binary search procedure, which works fine. I added a simple if-else statement at the end of my proc and it just doesn't fire! I can't see anything wrong with it and am embarrassed to have to say I am stuck. Please help!

procedure BinSearch;
var
  min,max,mid, x: integer;
  A : array[0..4] of integer;
  rslt : integer;

begin

  writeln('binary search');
  A[0] := 34; A[1] := 65; A[2] := 98; A[3] := 123; A[4] := 176;
  listarray(a);
  x := 62;
  min := 0;
  max := 4;

  repeat
    begin
    mid := (min + max) div 2;
    if x > A[mid] then
      min := mid + 1
    else
      max := mid - 1;
    end;
  until (A[mid] = x) or (min > max);

  writeln(mid);
  writeln(a[mid]);

  if A[mid] = x then
    rslt := mid
  else
    rslt := not mid;

  if 54 = 65 then
    rslt := mid
  else
    rslt := not mid;

end;

It's the if A[mid] = x then one that won't fire. when debugging neither true or false branches fire, the debugger just skips straight over them. Also the if 54 = 65 then which is just a test does the same.

The if inside my repeat loop works fine though.

If I copy the problem if statement into a mini test proc, and then call the proc it works, so it makes me think it's something else in the proc like a missing ; causing something strange to happen but I cannot see it. Please help!

like image 438
user235325 Avatar asked Dec 20 '09 00:12

user235325


1 Answers

The Delphi compiler is pretty smart, and it will happily remove unused code. When I compile your code I get compiler hints saying "Value assigned to 'rslt' never used". Since the value is never used, the compiler just skips over those statements.

If you add a Writeln(rslt); to the end of your procedure, you will find that the debugger will now trace through your if statement.

like image 82
Incredulous Monk Avatar answered Oct 13 '22 11:10

Incredulous Monk