RE: c question



On  1 Oct, Chris Jones wrote:
:  
:  Why not just do:
:  
:  void function( char *string )
:  {
:  	if( string == NULL ) {
:  		string = strdup( "default" );
:  	}
:  
:  	/* ... */
:  
:  	free( string );
:  
:  }
:  
:  int main()
:  {
:  	function( "moo" );
:  	function( NULL );
:  }
:  
:  it does mean that you can't just call "function();" - you have to put
:  a NULL as the argument, but it works just fine.

Until you get to free( string ), you were good up to there. In the two
examples above, the first would try to free() a string constant (bad)
the second would try to free() NULL (also bad). Generally I don't think
you want to free() something passed to you as a parameter because you
don't always know how it was allocated. If there is a special case when
that is what you want, it should be clearly documented, then the
crashes can be blamed on the application programmer...

Michael's suggestion is probably the best for making default parameters.

	- A




[Date Prev][Date Next]   [Thread Prev][Thread Next]   [Thread Index] [Date Index] [Author Index]