Name

$Warnings Compiler Directive

Syntax

{$Warnings On}  // default
{$Warnings Off}

Scope

Local, applies to entire subroutine

Description

The $Warnings compiler directive enables or disables compiler warnings. The compiler issues warnings for code that appears to be incorrect without actually violating any of the syntax rules for Delphi Pascal. For example, the compiler issues a warning if a subroutine uses a variable before the variable is assigned any value. Or a subroutine might not return a value in all situations. If you know the warning is unfounded, you can suppress it with the $Warnings directive.

Tips and Tricks

  • You should not disable compiler warnings globally in a file or project. The compiler warnings are useful and can warn you about numerous common errors. Disable warnings only when you know it is safe, and then disable them only for the subroutine in question.

  • Instead of disabling warnings, try to rewrite the code so the compiler does not generate a warning. Sometimes this means writing code that you know is dead and will never be executed, but the alternative is usually worse. When you disable warnings, you might be hiding a warning for an error you don’t know about.

Example

// Disable the warning about Result being undefined.
{$Warnings off}
function RunProgram(const Path: string): DWORD;
var
  Code: DWORD;
  StartupInfo: TStartupInfo;
  ProcessInfo: TProcessInformation;
begin
  FillChar(StartupInfo, SizeOf(StartupInfo), 0);
  StartupInfo.cb := SizeOf(StartupInfo);
  if not CreateProcess(PChar(Path), nil, nil, nil, False, 0, nil, nil,
                       StartupInfo, ProcessInfo)
  then
    RaiseLastWin32Error
    // Raises an exception, so the function never returns, and the
    // result doesn't matter.
    // Using $Warnings is one solution; another is to set Result here.
    // The dead code satisfies the compiler and doesn't have the problem
    // of disabling warnings for the entire function.
  else
  begin
    WaitForSingleObject(ProcessInfo.hProcess, Infinite);
    GetExitCodeProcess(ProcessInfo.hProcess, Code);
    Result := Code;
  end;
end;
{$Warnings on}

See Also

$Hints Compiler Directive
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset