Re: help a beginner with a basic function that should return a char



praveen21 <praveen.panday@xxxxxxxxx> writes:

On Jul 11, 7:40 am, pete <pfil...@xxxxxxxxxxxxxx> wrote:
<snip>
char * getvalue(unsigned u)
{
     char *a[] ={"even","odd"};

     return a[u % 2];

}


perfect code

I don't want to sound churlish (and, unprompted, I would not have said
a word about this fine posting) but "perfect" is a strong word to use.

Did you notice that pete (who, quite reasonably, wants to write
portable C90 code) has had to chance the specification of the function
so that now it takes an unsigned int? Do you know why? I am pretty
sure it is simply so that indexing the array with u % 2 is always 0 or
1. If u were a signed int, the result on some systems can be -1. Of
course he could have written:

char *a[] = {"even", "odd"};
return a[abs(i % 2)]; /* i now signed int again */

or used a three-element array indexed with a % 2 + 1, but the original
is neater. This kind of subtlety -- the need to use unsigned types --
is the kind of detail that merits a comment.

On a related issue, if a function had to return one of two numbers
based some binary condition, would you put them into an array and then
index the array:

double either[] = {2.71828, 3.14159};
return either[i % 2];

? Personally, I wouldn't. I'd use a conditional expression, and I'd
do the same in the original case.

Finally, I'd prefer that the return type of the function be 'const
char *' and that it have a better name, although neither may be
permitted if the specification is fixed.

const char *parity(int i)
{
return i % 2 ? "odd" : "even";
}

Of course, pete never claimed (and I am certain he never would claim)
that his code was perfect; and I certainly don't make that claim for
my silly one liner, but it seems worth posting if only to show that
there is more to learn by having a debate about code than by labelling
it.

--
Ben.
.



Relevant Pages