Mega Code Archive

 
Categories / Delphi / Ide Indy
 

Bug in Delphi (4,5 & 7 tested)

Title: Bug in Delphi (4,5 & 7 tested) Question: You've written a function that returns a string BUT you forget to assign the value to Result. It doesn't give a compiler warning and does not change the variable that is assigned. Answer: To show this drop a button on a form, click it and add the following code: function RemoveAfterDot(str : string):string; var p : integer; begin p := pos('.', str); if p 0 then begin Result := copy(str,1,p-1); end; end; function StripDot(str : string) : string; begin Result := 'Wrong'; Result := RemoveAfterDot(str); end; procedure TForm1.Button1Click(Sender: TObject); begin ShowMessage(StripDot('Correct')); end; If you try this, it compiles (No warning!) and when you run it, you will get Wrong! Add a dot to 'Correct' as in 'Correct.' and it will output Correct. Despite the 2nd assignment in StripDot, it does NOT. This can lead to very subtle bugs! Now a function that doesn't set Result is obviously wrong (Help says its undefined), but if you change the strings to integers you will get compiler warnings and the 2nd Result assigned in StripDot will be changed. So be warned!