delphioptimization

Delphi constant bitwise expressions


Probably a stupid question, but it's an idle curiosity for me.

I've got a bit of Delphi code that looks like this;

const
  KeyRepeatBit = 30;

...
  // if bit 30 of lParam is set, mark this message as handled
  if (Msg.lParam and (1 shl KeyRepeatBit) > 0) then
    Handled:=true;
...

(the purpose of the code isn't really important)

Does the compiler see "(1 shl KeyRepeatBit)" as something that can be computed at compile time, and thus it becomes a constant? If not, would there be anything to gain by working it out as a number and replacing the expression with a number?


Solution

  • Yes, the compiler evaluates the expression at compile time and uses the result value as a constant. There's no gain in declaring another constant with the result value yourself.

    EDIT: The_Fox is correct. Assignable typed constants (see {$J+} compiler directive) are not treated as constants and the expression is evaluated at runtime in that case.