What is the assert() method in D programming?

Overview

We can easily check the value and range of values for any variable’s value using the assert method in D language. This function can serve as the condition for any conditionals.

The assert() method

The assert() method is a function that can be used to create a condition for the acceptable values of the expression or variables. It can also mandate that a variable is bound by a stated rule for its value and so on.

We can use the assert() method to make assertions, which confirms that the variable’s expression follows the assert condition.

Syntax

assert(assertion_expression,text)
  • assertion_expression is the expression/condition which makes the assertion.
  • text is any text we would want to output to the screen. For example, we can assert that variable A is equal in value to variable C just to make sure that it is really so.

Return value

It returns true on a true assertion and false if the assertion condition was defied.

import std.stdio;
void main(){
//declare some variables
int y;
int x;
//mandate type of values for the variables using assert
assert(y > 8, "y cannot be less or equal to 8");
assert(x >= 0, "x cannot be negative!");
//give these variables wrong values and it throws error
y = 4;
x = -4;
}

Explanation

The code snippet above is an illustration of an assert failure. The assert() method will throw an assert failure error message once the assertion is not true. If successful, it will return true and no error will be thrown.

  • Line 1: We import the std.stdio library package.

  • Line 3: We start the main function that returns void.

  • Lines 5 and 6: We declare variables.

  • Lines 8 and 9: We create an assert condition for the possible and allowable values of the variables that have been declared using the assert() method.

  • Lines 12 and 13: We give the values that defy the conditions that have been asserted to the declared variables.

Below, we’ll look at another code snippet, where the assert function executes successfully.

Code

An assert() method will runs without throwing errors when the values provided do not defy the assert specification.

import std.stdio;
void main(){
//declare some variables
int [] y = [7,6,7,8,9];
writeln (y[4]);
assert(y[4] == 9, "y cannot be less or equal to 8");
}

Explanation

In the code above, we see the following.

  • Line 1: We import the std.stdio library.
  • Line 3: We start the main function block.
  • Line 5: We declare variable y as an integer.
  • Line 7: We display the value of y at index 4.
  • Line 8: We make an assert() operation which returns as true.