Sujet : Challenge/exercise problem - signum() function
De : tr.17687 (at) *nospam* z991.linuxsc.com (Tim Rentsch)
Groupes : comp.lang.cDate : 12. Aug 2024, 16:17:11
Autres entêtes
Organisation : A noiseless patient Spider
Message-ID : <868qx193ew.fsf_-_@linuxsc.com>
References : 1 2 3 4
User-Agent : Gnus/5.11 (Gnus v5.11) Emacs/22.4 (gnu/linux)
Vir Campestris <
vir.campestris@invalid.invalid> writes:
On 12/08/2024 01:43, Tim Rentsch wrote:
>
[...]
Also, it would be better for your understanding of C if you would
stop thinking about what is going on at the level of actual
hardware. Doing that serves to confuse a lot more than it helps.
>
I think I feel my ears burning!
I'm taking that as a compliment. :)
Also as an impetus to post a small C exercise I've been meaning
to put up.
The goal is to write a C function to compute a signum() value:
long
signum( long k ){
/* should return
* -1 if k < 0
* +1 if k > 0
* 0 otherwise
**/
/* ... */
return 0; /* appropriate return value to be supplied */
}
Of course such a function is trivial to write. The challenge
part is to write one that observes the following restrictions:
* must work on any conforming C90 or C99 implementation,
including freestanding implementations. (Hence _Bool
is out of bounds.)
* statements must be limited to expression statements and
one return statement at the end of the function (simple
declarations are also okay).
* no conditional compilation (#if, #ifdef, #ifndef, etc)
* no pointers, casts, unions, or user-defined types
* all operators that return "logical" values are off
limits: must not use !, <, <=, >, >=, ==, !=, &&, ||, ?:
To make things easier, you may assume 'long' has no padding
bits, and no trap representations (there may be negative
zeros though).
That's it. Should provide some fun for those who want to
try it.