CSC161 2010F, Class 26: Program Correctness and assert Overview: * Programming by Contract. * Questions. * assert. * Lab. Admin: * Carrots! * Hippo Birdies 2 Ewes * For tomorrow, read Summary and Sample Session from the DDD Manual, available at some random URL. * Belated EC for The Contingency Play. * Are there questions on Assignment 5? Questions on Assignment 5: * HOw do I compare two arrays? With a for loop? * How do I know that my comparison works? Unit test it! * Can we go through selection sort Programming by Contract. * Primary point? * Preconditions and postconditions are important * And we knew that already * Pre and post are important because they tell us when parameters and such are wrong * We can use preconditios and postconditions to ensure that our sequence of actions is reasonable: If the postconditions of one statment match the preconditiosn of the next, that part of our program is safe. If every part is safe, the whole program is safe. * This also seems related to testing - We should ensure that the result matches the postconditions. * If we check for preconditions and postconditions everywhere, our program should work our we know why it doesn't. How do we incorporate preconditions and postconditiosn in our program? * Check preconditions * Simply state them, as in the six P's - it's a contract; if the caller/client ignores the preconditions, we can do whatever we'd like * Checking preconditions can make the program slow and unwieldy * Not all preconditions are testable, and some tests are quite expensive * Good analysis suggests that the prconditions are met * Use pre and post with an automatic analyzer * Check postconditions What should happen if a precondition fails? * Return whatever you feel like * Don't call the procedure (if checked in client) * UM * Report what went wrong * printf if it's something the user can do something about * Report to the caller int findActivistBlondStudent (student[]) * Identify some value as "this is an error" and return that value -1 is a good error number if results can only be nonnegative 0 is a good error number b/c it means "false" INT_MIN * What if all return values are legal, as in the case of atoi? * Set a global variable * Choose a different control flow: Call the "You bozo, you screwed up" recovery routine - throw Exceptions (not quite easy in C) What should we do if we want to check whether or not a string can be converted to an integer? * sscanf (str, "%d", &x) as an alternative to x = atoi(str) In C, one way to check preconditions and postconditions is with the assert statement assert (expression); * Evaluates the expression * Succeeds (nonzero result) - Does nothing else * Fails (zero result) - Prints an error message and kills the program You can turn off assert Consider assert (sscanf (argv[1], "%d", &x) == 1); This says "Try to read the value from argv[1] into x. If it succeeds, sscanf returns 1, so the assert succeeds. If sscanf fails, it returns 0, so assert fails. Lab.