From: Matju Date: 2004-11-12T04:59:05+09:00 Subject: Re: Converting nil to NULL On Fri, 12 Nov 2004, Berger, Daniel wrote: > I asked this on ruby-talk, but I thought I should ask here as well. > I find I'm often doing something like this: > static VALUE foofoo(int argc, VALUE* argv, VALUE self) > char* foo; > VALUE rbFoo; > rb_scan_args(argc,argv,"01",&rbFoo); > if(NIL_P(rbFoo)){ > foo = NULL; > } > else{ > foo = StringValuePtr(rbFoo); > } > Is there a way to reduce this to a single step? Can we modify > StringValuePtr() to return NULL if its argument is nil? Or would that > break too many things? In addition to Charles' solution, which is good, I'd like to say that the conditional expressions of C are not evil. You can write: foo = NIL_P(rbFoo) ? NULL : StringValuePtr(rbFoo); and it _wouldn't_ be a crime and it wouldn't make little Jesus cry. After all, Ruby has _eight_ different kinds of conditional expressions (the ?: syntax, the if/end syntax, and the "&&"/"||"/"and"/"or"/"if"/"unless" binary operators), which is slightly more than in PERL. I don't mean it's right to have so many options syntax-wise, but rather that if there are so many, then it's surely not considered evil in the Ruby culture. This kind of relativity prompts to reconsider the rule in the C culture. If you follow a certain coding standard that forbids conditional expressions, let me tell you, the purpose of a coding standard is to make things smoother, and not cumbersome. All that said, it's still better to make a function or macro out of this, especially if you do it very often. In my biggest C++ program I go as far as... well... just imagine what it would like if rb_scan_args had a full, user-extensible type conversion system. THEN you can cut down a _lot_ on code, as you wouldn't even have to call StringValuePtr directly, neither your own NULL-savvy wrapper. Preserves the brain for the more challenging aspects of programming. _____________________________________________________________________ Mathieu Bouchard -=- Montr�al QC Canada -=- http://artengine.ca/matju