Search code examples
delphiconstantscompiler-warnings

Why there is no warning or hint when a constant is not used?


I was trying to show some code to another person when I subtly perceived that beside when declared variables are not used there is compiler hint messages, there is no hints or messages when a declared constant is not used. Following code is an example:

program Project1;

{$APPTYPE CONSOLE}

uses
  SysUtils,
  Math;

const
  intM: Integer = 1000;

var
  valorDouble, notusedvar: Double;

begin
  try
    valorDouble   := 0.001;
    Writeln('--- Codigo atual --');
    Writeln('Double   -> ', Trunc(valorDouble   * 1000));
    Writeln('--- Correcao?? --');
    Writeln('Trunc(1.0000001) -> ', Trunc(1.0000001));
    Writeln('Trunc(0.001 * 1000.0)   -> ', Trunc(0.001 * 1000.0));
    Writeln('Trunc(0.0010 * 1000.0)  -> ', Trunc(0.0010 * 1000.0));
    Writeln('Trunc(0.00100 * 1000.0) -> ', Trunc(0.00100 * 1000.0));

    Readln;
  except
    on E: Exception do
      Writeln(E.ClassName, ': ', E.Message);
  end;
end.

Why there is no hint about the not used constant? There is any logical explanation about this difference?


Solution

  • Let's jump straight into an example. Let's say you're writing a DLL with 1 exported function. One of those function's parameters is an integer...

    procedure DoSomething(const Value: Integer); stdcall;
    

    Now let's say you have defined multiple constants to represent all possible integer values this function might recognize...

    const
      CON_ONE = 1;
      CON_TWO = 2;
      CON_THREE = 3;
      //Maybe hundreds
    

    Now let's say when you implement this function, you only really need the first one CON_ONE but not the other two. Would you really want a hint for every one of these?

    More realistic example is things like HKEY_LOCAL_MACHINE, HKEY_CURRENT_USER, etc. which come with Delphi (tied to Windows API calls). Just take a look at all the constants in Windows.pas. Imagine if all of these possible constants raised a compiler hint.

    Essentially, when you get a compiler hint of an unused variable, it most often means a coding error (or just something you forgot to delete), whereas an unused constant typically means just an unimplemented capability.