Book Image

D Cookbook

By : Adam Ruppe
Book Image

D Cookbook

By: Adam Ruppe

Overview of this book

Table of Contents (21 chapters)
D Cookbook
Credits
Foreword
About the Author
About the Reviewers
www.PacktPub.com
Preface
Index

Using static asserts


A static assert is the main language feature for implementing custom compile-time checks. It can check any condition. If the static assert is compiled, the condition must be true; otherwise, it will issue a compile-time error. Here, we'll use it to verify whether our struct is of the correct size to interface with hardware.

How to do it…

Perform the following steps:

  1. Write static assert(condition, message); in the code.

  2. If your condition is too complex to represent as a simple condition, you may write a helper function and call it for the condition.

  3. Remember that static assert must pass if the code is compiled, even if the path is not actually executed.

The code is as follows:

align(1) struct IDTLocation {
  align(1):
  ushort length;
  uint offset;
}
static assert(IDTLocation.sizeof == 6, "An IDTLocation must be exactly six bytes with no padding.");

How it works…

The compile-time partner to assert is static assert. It functions in the same way, but instead of checking a runtime...