Set8087CW (Delphi)

From RAD Studio Code Examples
Jump to: navigation, search

Description

This example accesses the Floating Point Unit (FPU) control register. Try turning floating point exceptions off and on and dividing a number by zero to test it.

Create a new VCL application and drop three edit controls, a button and a radiogroup on to the form. Add two string items to the radio group, 'FPU Exceptions' and 'No FPU Exceptions'. Double-click the button to define the Click event method defined as TForm1.Button1Click below, then double-click the radiogroup and define TForm1.RadioGroup1Click as seen below. Double click the form and define TForm1.Create in the same fashion. From the Object Inspector, double-click FormDestroy and then define TForm1.FormDestroy, also as seen below.

Following these steps and running the resulting application, you will find a form with three edit controls, a radio group describing floating-point exceptions, and a button that takes floating-point values in the first two edit controls, divides them and places the result in the third.

How the program runs depends on the values of the radio group. For instance, if the second edit control holds a value of 0.0, an exception is expected to be raised when "FPU Exceptions" is selected in the radio group, but an exception will not appear if "No FPU Exceptions" is selected. The System.Set8087CW function controls this behavior.

Notice that in TForm1.FormDestroy the default value of the FPU control is restored. This is vitally important, as the FPU is a shared resource, and any deliberate change in its behavior will affect all code depending upon it. In this case, restoring the control word restores the raising of exceptions during floating point operations.

Code

var
  Form1: TForm1;
  Saved8087CW: Word;

implementation

{$R *.dfm}

procedure TForm1.Button1Click(Sender: TObject);
begin
  Edit3.Text := FloatToStr(StrToFloat(Edit1.Text) / StrToFloat(Edit2.Text));
end;

procedure TForm1.RadioGroup1Click(Sender: TObject);
begin
  if RadioGroup1.Items[RadioGroup1.ItemIndex] = 'FPU Exceptions' then
    System.Set8087CW(Saved8087CW);
  if RadioGroup1.Items[RadioGroup1.ItemIndex] = 'No FPU Exceptions' then
    System.Set8087CW($133f); { Disable all fpu exceptions. }
end;

procedure TForm1.FormCreate(Sender: TObject);
begin
  RadioGroup1.Items.Add('No FPU Exceptions');
  RadioGroup1.Items.Add('FPU Exceptions');
  RadioGroup1.ItemIndex := 2;
  Saved8087CW := Default8087CW;  // Save this because Set8087CW changes it.
end;

procedure TForm1.FormDestroy(Sender: TObject);
begin
  System.Set8087CW(Saved8087CW); // Default value (with exceptions) is $1372.
end;

Uses

See Also