Testing and Debugging
Assert Condition
A checked condition can protect the line that depends on it.
precondition
A precondition is a fact the next operation needs before it is safe.
checked path
Checking the condition first lets the program report the problem instead of using a bad value.
Assert Condition
assert_condition.c
Replay: real traced execution (multi-file project)
#include <stdio.h>
int main(void) {
int value = 6;
int ok = value > 0;
if (ok) {
int quotient = 120 / value;
printf("ok=%d quotient=%d\n", ok, quotient);
} else {
printf("ok=%d quotient=skipped\n", ok);
}
return 0;
}
#include <stdio.h>
int main(void) {
int value = 0;
int ok = value > 0;
if (ok) {
int quotient = 120 / value;
printf("ok=%d quotient=%d\n", ok, quotient);
} else {
printf("ok=%d quotient=skipped\n", ok);
}
return 0;
}
#include <stdio.h>
int main(void) {
int value = 10;
int ok = value > 0;
if (ok) {
int quotient = 120 / value;
printf("ok=%d quotient=%d\n", ok, quotient);
} else {
printf("ok=%d quotient=skipped\n", ok);
}
return 0;
}
value ← 6, ok ← 1
3int main(void) {4 int value→ 6 = 6; //@value=0, 105 int ok→ 1 = value6 > 0;quotient ← 20
7if (ok1) {8 int quotient→ 20 = 120 / value6;9 printf("ok=%d quotient=%d\n", ok1, quotient20);10} else {outputok=1 quotient=20return 0;
14 return 0;15}
value ← 0, ok ← 0
3int main(void) {4 int value→ 0 = 0;5 int ok→ 0 = value0 > 0;else
9 printf("ok=%d quotient=%d\n", ok, quotient);10} else {11 printf("ok=%d quotient=skipped\n", ok0);12}outputok=0 quotient=skippedreturn 0;
14 return 0;15}
value ← 10, ok ← 1
3int main(void) {4 int value→ 10 = 10;5 int ok→ 1 = value10 > 0;quotient ← 12
7if (ok1) {8 int quotient→ 12 = 120 / value10;9 printf("ok=%d quotient=%d\n", ok1, quotient12);10} else {outputok=1 quotient=12return 0;
14 return 0;15}