Re: Why C++ is vastly superior to C
gwowen <gwowen@gmail.com> writes:
example given in the article, if you're making a linked list of
dynamically allocated object, and the system runs out of memory on n-
th object then you need to make sure the previous n-1 objects are
correctly deallocated at the error. In C, that's definitely possible,
but its quite unpleasant - not least because your unwinding code will
likely need to be close to the creation code, which makes your code
harder to read.
I think that the unwinding code /should/ be close to the
creation code, /because/ that will make the whole code
easier to read. So, in C,
/* Enlarge a list by appending n new entries to it, all of which just
contain a dummy null pointer for the purpose of this example.
When it is detected that a new entry cannot be append anymore
(for example due to lack of memory), the entries appended so far
will be removed and the function will return a nonzero value. */
int enlarge_list( list_t * const list, int const n /* precond: i > -1 */ )
{ int result = 1; int i; /* result == 0 means success */
for( i = 0; i < n; ++i ) /* append n new entries to the list */
if( list_push( list, 0 )) /* appends a null pointer to the list */
break; /* break on error to push a new entry */
if( i < n )list_pop( list, i ); /* clean up by removing all appended */
else result = 0; /* or else set the value for success */
return error; }
(untested.)