Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 346
robsoft Avatar asked Jul 22 '09 10:07

robsoft


2 Answers

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.

like image 64
Ondrej Kelle Avatar answered Sep 21 '22 01:09

Ondrej Kelle


You can make sure iike this, for readability alone:

const
  KeyRepeatBit = 30;
  KeyRepeatMask = 1 shl KeyRepeatBit ;
like image 35
Henk Holterman Avatar answered Sep 25 '22 01:09

Henk Holterman