A silly little utility

Max Okumoto okumoto at ucsd.edu
Mon Aug 22 13:53:27 PDT 2005

walt wrote:
This was inspired by the kde version of xterm, which allows
each new window to be opened with a random pastel-colored
This program ('rlc' --> random-light-colors)
generates ascii strings of the form 'rgb:hh/hh/hh' which
can be used to open an xterm window like this:
xterm -bg `rlc`

The source is listed below.  I have a few bonehead 'c'
questions, however:
Why does this program compile without including stdio.h ?
You should include stdio.h because you are using printf().
The code still compiles because none of it depends on any
data types, and printf() works most of the time since only
fixed sized object are passed to it.
But since there is no prototype in scope the compiler can
not help you find problems like:
	printf(10, "Hey printme!");

Look at the CWARNFLAGS in /usr/share/mk/bsd.sys.mk and use
the attach Makefile.  The compiler will provide more warning
and will help you cleanup the code.  You can find description
for the warning flags in the gcc man page.
Does it matter if the variable declarations come before
or after 'main()'?
The variables should be declared in the scope of main() not
in global scope.  Global variables should be avoided, unless
there is a need for them.
Any problems with the style or the logic of the code?
You want to describe what the intent of the code is.  Someone
reading your code can see what the code itself does.  But they
can not determine why you made those desicsions.
#include <stdio.h>

        int n,r,g,b;	/* red, green, blue */
	int offset = 0xe0;
	/* initialize random number generator */
	/* generate random bits, but keep only 15 bits for the color */
	n = 0x7fff & random();
	 * Extract 5 bits from the random number for each color, and
	 * add an offset to each color to make the result pastel.
	 * The range of each color is 0 to 255. (8 bits)
	r = (n & 0x1f) + offset;
	n >>= 5;
	g = (n & 0x1f) + offset; 
	n >>= 5;	
	b = (n & 0x1f) + offset;

	printf("rgb:%x/%x/%x\n", r, g, b);
	return (0);
Note: if this code is too slow you can optimize the code, by using
      the logical-or operation once. ;-)
	n = 0xffffff & random();
	n |= 0xe0e0e0;
 	r = (n & 0xff);
 	n >>= 8;
 	g = (n & 0xff);
 	n >>= 8;	
 	b = (n & 0xff);
PROG	= rlc
SRCS	= main.c
NOMAN	= true		# there is no man page for this program

#	Turn on more warnings and fail if there were any warning generated. 

#	Use BSD make utilities.
. include <bsd.prog.mk>

More information about the Submit mailing list