The Friday Fragment

It’s Friday, and time again for a new Fragment: my weekly programming-related puzzle.

This Week’s Fragment

This week’s programming puzzle was sent in by Joel Odom:

Write C code or pseudo-code to swap the values of two integer (int) variables, a and b, without declaring or using any other variables. Do not use any syntactical language tricks that implicitly copy values out of a or b into other memory or registers.  You can use C operators, control flow, and similar statements.

If you want to “play along”, post the solution as a comment or send it via email.   To avoid “spoilers”, simply don’t expand comments for this post.

Last Week’s Fragment – Solution

Last week’s puzzle was the following programming-related cryptogram:

Baae jaanklb xpnrv xksr.  Ki gaq pwr sper xa cpkx, kx kv xa vrwhr gaq urxxrw, ple xa ftrpvr gaq.

Congratulations to Luke for solving this; the plaintext answer is:

Good cooking takes time.  If you are made to wait, it is to serve you better, and to please you.

This is a chapter intro quote in Fred Brooks’ classic The Mythical Man Month, taken from a French restaurant menu.  It reminds us that quality software also requires time and careful preparation.

1 Comment

DerekJune 4th, 2010 at 9:10 pm

Here are the solutions I submitted to Joel:

I thought of two solutions: XOR’ing (since xor’ing twice gets the value back), and calling a function (using the stack to push/pop at least one of the values). Here’s code that uses both approaches:

#include <stdio.h>

main() {
   int a=1, b=2;
   a=a^b;
   b=b^a;
   a=a^b;
   printf("a=%d, b=%d\n", a, b);
   a=swap(a, b, &b);
   printf("a=%d, b=%d\n", a, b);
}

int swap(int a, int b, int *bp) {
   *bp=a;
   return b;
}

If you had something else in mind, let me know or post it.

And here's Joel's response:

The first solution, with the XOR is what I had in mind. Some guys at work and I came across this the other day. The function call is a good idea, but it allocates memory on the stack, so it's kind of like cheating. :-)