In C, the preprocessor makes it possible to do some computations at compile time. If the C compiler supports #pragma message
, it can even output the result at compile-time. Of course, whether this works well depends on the compiler.
The following program is a compile-time version of the classic "99 bottles of beer" program. It works well with the Digital Mars C compiler. Some compilers, such as at least some Borland compiler versions, may treat the messages as warnings and thereby overrun the maximum number of warnings to generate.
#ifndef T
#define T(x) #x
#define tens 9
#define units 9
#define line(x, y) T(x) T(y) " bottles of beer"
#endif
#pragma message(line(tens, units) " on the wall")
#pragma message(line(tens, units))
#pragma message("Take one down, pass it around")
#if units == 9
# undef units
# define units 8
#elif units == 8
# undef units
# define units 7
#elif units == 7
# undef units
# define units 6
#elif units == 6
# undef units
# define units 5
#elif units == 5
# undef units
# define units 4
#elif units == 4
# undef units
# define units 3
#elif units == 3
# undef units
# define units 2
#elif units == 2
# undef units
# define units 1
#elif units == 1
# undef units
# define units 0
# if tens + 0 == 0
# define END
# endif
#else
# undef units
# if tens == 9
# undef tens
# define tens 8
# elif tens == 8
# undef tens
# define tens 7
# elif tens == 7
# undef tens
# define tens 6
# elif tens == 6
# undef tens
# define tens 5
# elif tens == 5
# undef tens
# define tens 4
# elif tens == 4
# undef tens
# define tens 3
# elif tens == 3
# undef tens
# define tens 2
# elif tens == 2
# undef tens
# define tens 1
# elif tens == 1
# undef tens
# define tens
# else
# define END
# endif
# define units 9
#endif
#if tens + 0 == 0
# if units == 1
# undef line
# define line(x, y) "1 bottle of beer"
# elif units == 0
# undef line
# define line(x, y) "0 bottles of beer"
# endif
#endif
#pragma message(line(tens, units) " on the wall")
#pragma message("")
#ifndef END
#include "99bottles.c"
#endif
Note that this code assumes that the file is named 99bottles.c.