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_expressionis the expression/condition which makes the assertion.textis 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 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;}
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.stdiolibrary package. -
Line 3: We start the
mainfunction that returns void. -
Lines 5 and 6: We declare variables.
-
Lines 8 and 9: We create an
assertcondition for the possible and allowable values of the variables that have been declared using theassert()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 variablesint [] 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.stdiolibrary. - Line 3: We start the main function block.
- Line 5: We declare variable
yas an integer. - Line 7: We display the value of
yat index 4. - Line 8: We make an
assert()operation which returns as true.