c++ - Am I misunderstanding assert() usage? -
i taking @ the assert()
reference page , got stuck while read given example:
/* assert example */ #include <stdio.h> #include <assert.h> int main () { file * datafile; datafile=fopen ("file.dat","r"); assert (datafile); fclose (datafile); return 0; }
in example, assert used abort program execution if datafile compares equal 0, happens when previous call fopen not successful.
i totally agree if fopen()
fails, assert()
abort execution. i'm concerned rightness of example:
in opinion assert()
there detect cases can't happen (like passing null
pointer function documentation states forbidden).
in example, failing open file not can't happen. in fact, can see dozens of reasons why fail. file couldn't exist, program run without required privileges, , on.
i rather have done like:
/* not longer assert example */ #include <stdio.h> #include <assert.h> int main () { file * datafile; datafile=fopen ("file.dat","r"); if (datafile != null) { // something, whatever. fclose (datafile); } else { // report error somehow. } return 0; }
is understanding of how assert()
should used incorrect ?
edit , news !
it seems referred site ruled rigorous people. here mail got 1 of site maintainer:
hi julien, have agree, example code poorly chosen. has been rewritten more appropriate.
many pointing out, , sorry inconveniences may have caused you.
best regards,
and updated example:
/* assert example */ #include <stdio.h> #include <assert.h> void print_number(int* myint) { assert (myint!=null); printf ("%d\n",*myint); } int main () { int a=10; int * b = null; int * c = null; b=&a; print_number (b); print_number (c); return 0; }
glad see people work on internet ! ;)
you're right sir. poor usage of assert
.
Comments
Post a Comment