Path: ...!eternal-september.org!feeder3.eternal-september.org!news.eternal-september.org!.POSTED!not-for-mail From: Tim Rentsch Newsgroups: comp.lang.c Subject: Challenge/exercise problem - signum() function Date: Mon, 12 Aug 2024 08:17:11 -0700 Organization: A noiseless patient Spider Lines: 53 Message-ID: <868qx193ew.fsf_-_@linuxsc.com> References: <86y152in9n.fsf@linuxsc.com> MIME-Version: 1.0 Content-Type: text/plain; charset=us-ascii Injection-Date: Mon, 12 Aug 2024 17:17:15 +0200 (CEST) Injection-Info: dont-email.me; posting-host="f42e4005105099d89c60a754521770ce"; logging-data="3530086"; mail-complaints-to="abuse@eternal-september.org"; posting-account="U2FsdGVkX1+OI5OFdv8tKqDHFQOXPDetSEUGJszfCpI=" User-Agent: Gnus/5.11 (Gnus v5.11) Emacs/22.4 (gnu/linux) Cancel-Lock: sha1:zQR3D3Q2rfprWkcFg1YSpbkOTQ0= sha1:dU3crBB1rY1fDjYQ1XJvCSy+gHk= Bytes: 2710 Vir Campestris 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.