Re: Why C++ is vastly superior to C
gwowen <gwowen@gmail.com> writes:
So, enlarge_list returns an error status .. and its caller checks it
and ... then what?
There can not be a general answer to this. It is the callers
decision.
Either the caller must then have its *own* error unwinding code, near
every call site, and it *must* have a return type suitable for
returning the error status of every function it calls,
Well, the details depend on what the caller is intended to do.
In the code below, for example, return values of functions
called are coalesced into an own return value. For example,
to read, sort and print a list using
http://mij.oltrelinux.com/devel/simclist/
(this code was not completely tested, it still might
contain bugs, but one can get the idea):
#include <stdio.h> /* scanf, printf */
#include <stdlib.h> /* EXIT_SUCCESS */
#include "simclist-1.4.3/simclist.h" /* list_... */
int appendvalue( list_t * const list, int *looping )
{ int value;
if( 1 != scanf( "%d", &value ))return 1;
if( value >= 0 )
{ if( list_append( list, &value )< 0 )return 2; }
else *looping = 0;
return 0; }
int read( list_t * const list )
{ int looping = 1; while( looping )
{ if( appendvalue( list, &looping ))return 1; }
return 0; }
int sort( list_t * const list )
{ if( list_attributes_comparator( list, list_comparator_int32_t ))return 1;
else if( list_sort( list, -1 ))return 2;
else return 0; }
int print( list_t * const list )
{ if( list_iterator_start( list )<= 0 )
return 1;
{ while( list_iterator_hasnext( list ))
{ void * next = list_iterator_next( list );
if( next )
{ if( printf( "%d\n", *( int * )next )< 0 )return 2; }
else break; }
if( !list_iterator_stop( list ))return 3; }
return 0; }
int main2( list_t * const list )
{ if( !list_attributes_copy( list, list_meter_int32_t, 1 ))
{ if( read( list ))return 1;
else if( sort( list ))return 2;
{ printf("Sorted values:\n");
if( print( list ))return 3; }}
return 0; }
int main1( list_t * const list )
{ int result;
if( list_init( list ))result = 1;
else
{ if( main2( list ))result = 2;
list_destroy( list ); }
return result; }
int main( void )
{ list_t list;
return main1( &list )? EXIT_FAILURE : EXIT_SUCCESS; }