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.
assert()
methodThe 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.
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.It returns true
on a true assertion and false
if the assertion condition was defied.
import std.stdio;void main(){//declare some variablesint y;int x;//mandate type of values for the variables using assertassert(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 errory = 4;x = -4;}
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.
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 variablesint [] y = [7,6,7,8,9];writeln (y[4]);assert(y[4] == 9, "y cannot be less or equal to 8");}
In the code above, we see the following.
std.stdio
library.y
as an integer.y
at index 4.assert()
operation which returns as true.