Recent

Author Topic: Compile time assert(ions)  (Read 1028 times)

440bx

  • Hero Member
  • *****
  • Posts: 6096
Compile time assert(ions)
« on: February 03, 2024, 01:02:16 pm »
Hello,

I know that run time assert is available.  I'd like to have compile time assert(s).  Are those possible ? if yes, an example would be more than welcome.

In particular, I'd like to assert at compile time that the size of some custom types is as expected, e.g, assert(sizeof(<sometypename>) = 16), presuming the expected size in this example is 16.  If the assert fails (the size is not 16) then stop the compilation with a fatal error message.

Thank you for your help.
FPC v3.2.2 and Lazarus v4.0rc3 on Windows 7 SP1 64bit.

Jonas Maebe

  • Hero Member
  • *****
  • Posts: 1071
Re: Compile time assert(ions)
« Reply #1 on: February 03, 2024, 01:27:12 pm »
Code: [Select]
type
  trec = record
    l: longint;
  end;

{$if sizeof(trec) <> 16}
  {$error sizeof(trec) is not 16}
{$endif}

begin
end.

There is no single-directive equivalent like static_assert or so.

440bx

  • Hero Member
  • *****
  • Posts: 6096
Re: Compile time assert(ions)
« Reply #2 on: February 03, 2024, 01:35:46 pm »
Code: [Select]
type
  trec = record
    l: longint;
  end;

{$if sizeof(trec) <> 16}
  {$error sizeof(trec) is not 16}
{$endif}

begin
end.

There is no single-directive equivalent like static_assert or so.
No problem.  As long as the condition can be checked, it's all good. :)

Thank you Jonas.
FPC v3.2.2 and Lazarus v4.0rc3 on Windows 7 SP1 64bit.

 

TinyPortal © 2005-2018