i working on assignment class, , think got program working properly, make modifications better understand assert. code below -
#include <iostream> #include <stdlib.h> #include <assert.h> using namespace std; // sample program shows how command line arg works, in unix g++ // note argc , argv // shows use of system call, can launch program // system launches 'ls' display files in dir void runassert(int); int main(int argc, char *argv[]) { cout << "number of inputs: " << argc << endl; cout << "1st argument: " << argv[0] << endl; system ("ls"); cout << "hello world" << endl; runassert(argc); return 0; } void runassert(int argc) { assert(argc > 4); } so program supposed keep track of arguments passed main through command line. professor specified should take 4 arguments. code works, far can tell, don't know 4 commands pass it? g++ assignment.cpp -o assignment , ./assignment -- last command counts 1 argument assert triggers. if change function >= 1 works.
another question have is, how can make display error message when doesn't meet requirements?
have tried assert("not right amount of arguments", argc > 4) error message many arguments being passed main.
thanks help, , sorry if formatting wrong. first time posting.
this incorrect usage of assert. use assert state things you, programmer, think logically necessary. logically possible call program fewer 4 arguments, assert not correct.
a common usage of assert @ start of function. (this not validating arguments.) consider int foo(void *k){ assert(k != null); ...} once again, not validating argument k. assertion piece of documentation tells human writing code @ call site foo not called null argument. claim in written code, logical necessity k non-null. if want validate argument , generate pretty error message, use if statement.
one thing assert should assume does not execute in normal operation. typically, program compiled -dndebug, turn of assertions whitespace.
Comments
Post a Comment