Bert said:
Well, this compiles on the compiler somewhere else wherever I sent
this to. Could you guys please point out which parts could be improved
oh and I just realised you're all professionals...um...could you
please INDICATE the points where I need to do all the error checking
like the try..catch kinda things for all kinds of exceptions (only C
doesn't have this cool stuff) like for adverse inputs? Thanks
C does not have support for exceptions so you need to check that each
library function you call has in fact succeeded. Each function has it's
own way of documenting failures; some return null pointers, others EOF,
still others return a count and so on. You should consult the
documentation for your Standard library and write in checks as
appropriate. A good on-line reference for the Standard library is
<
http://www.dinkumware.com/manuals/>.
What you do when a function has failed will obviously be highly
dependant on the exact situation, but for small test programs (like
yours) you might want to print a useful message printing what went
wrong and where (function and source line number) and probably, exit.
Recovery strategies (even if they are possible) may be too advanced at
this point.
An example:
if (fscanf(file, "%d", &i) != 1) {
fprintf(stderr, "%s (%d): fscanf() failed.\n",
__FILE__, __LINE__);
exit(EXIT_FAILURE);
}
With C99 you can also use the predefined identifier __func__ to extract
the name of the current function (as a string).
For checking the internal consistency of the program you can use the
macro assert in assert.h. If the expression passed to assert evaluates
to zero (logically false), assert will print a message and abort the
program. You can define the macro NDEBUG *prior* to including assert.h
to turn off all assertions.
Many library functions also set the object 'errno' to some integer value
upon failure. To use this mechanism you need to include the header
errno.h and set errno to zero before the function in question is
called. Immediately after you need to check errno for the presence of
documented error values (like ERANGE, EDOM, EILSEQ and other
implementation defined values), and if so, take appropriate action. You
can translate the error codes in errno to implementation specific
messages using the strerror or perror.
In addition to all this C99 has added considerable diagnostic facilities
for floating point and maths functions; consult the Standard for
details.
Draft of C1x <
http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1256.pdf>
<snip>