Monthly Archives: October 2012

C code that could get you fired

Here’s another stupid C trick I’ve carried around in my brain for a while:

#define sizeof(x) (rand() % 20 + 1)

The mod and addition are to give a random number in the range from 1 to 21.

This can be demonstrated with a small program:

#include <stdlib.h> 
#include <stdio.h>

#define sizeof(x) (rand() % 20) + 1

void main()
  int i;
  printf("Sizeof i: %d\n", sizeof(i));
  printf("Sizeof i: %d\n", sizeof(i));
  printf("Sizeof i: %d\n", sizeof(i));

When run, you get:

# ./random_sizeof
Sizeof i: 4
Sizeof i: 7
Sizeof i: 18

Your compiler might warn you about this, although mine didn’t (using GCC 4.3.2 with no flags) – but on a large project, there are probably so many warnings that an extra one wouldn’t be noticed anyhow (if all the large projects you’ve worked on had no warnings at all, you’re luckier than most of us).

Unlike the trick I posted previously, using this in your code will not have your colleagues worry about your competence so much as it will prompt them to fill a box with your things and show you the door…

Leave a Comment

Filed under code

Wherein 2 is shown to be equal to 1

Here’s a little maths trick I have for some reason carried around in my brain for years:

\text{Let } a = b
\Rightarrow a^2 = ab
\Rightarrow a^2 - b^2 = ab - b^2
\Rightarrow (a + b)(a - b) = b(a-b)
Dividing through by the common (a - b)
\Rightarrow (a + b) = b
\text{But } a = b
\Rightarrow (b + b) = b
\Rightarrow 2b = b
\Rightarrow 2 = 1

Why this is possible is left as an excercise for the reader 🙂


Filed under geekery

C code you should never use in production

I’ve been meaning to write this little trick down for a while, so while I remember to, here’s a stupid little C trick which amuses me.

Consider a C array:

char array[3] = {1,2,3};

To access element 3, you would use


This is just shorthand for a pointer dereference

*(array + 2)

This is just addition, which is associative, so it’s the exact equivalent of

*(2 + array)

which gives you


which is perfectly valid C.


To prove that, consider this simple program

void main()


char array[3] = {1,2,3};

printf("array[2]: %d. 2[array]: %d\n", array[2], 2[array]);

After compilation

array[2]: 3. 2[array]: 3


I would strongly caution against ever using this in production. Your colleagues will worry about you if they see it during a code review or when working on code you wrote. If you don’t think they would flag it, you should be worrying about them 🙂


Filed under code