09 Assertions
09 Assertions
//n == 1
while (n < limit) {
n = 2 * n;
}
// what could you state here?
What is an assertion?
An assertion is a statement that says something about
the state of your program
Should be true if there are no mistakes in the program
//n == 1
while (n < limit) {
n = 2 * n;
}
//n >= limit
//more?
What is an assertion?
An assertion is a statement that says something about
the state of your program
Should be true if there are no mistakes in the program
//n == 1
while (n < limit) {
n = 2 * n;
}
//n >= limit
//n is the smallest power of 2 >= limit
assert
Using assert:
assert n == 1;
while (n < limit) {
n = 2 * n;
}
assert n >= limit;
//n is the smallest power of 2 >= limit.
When to use Assertions
We can use assertions to guarantee the
behavior.
if (i % 3 == 0) { ... }
else if (i % 3 == 1) { ... }
else { assert i % 3 == 2; ... }
int p=..,d=..,r,q;
q = p/d;
r = p%d;
assert ??
Control Flow
If a program should never reach a point,
then a constant false assertion may be used
void search() {
for (...) {
...
if (found) // will always happen
return;
}
assert false; // should never get here
}
Assertions
Syntax:
assert Boolean_Expression;