[net.misc] Simple C Puzzle

dmy (12/29/82)

/* This is a (fairly) simple puzzle.
   Why does this program print "1" instead of "2"?
   Note: (1/1)+1 == 2 not 1
*/

main()
{
int a,b,*p;
	b= 1;
	p= &b;
	a= b/*p;
	++a /* oh? */;
	printf("%d\n",a);
}

/*
--dmy--
*/

laman (12/30/82)

The a++ gets swallowed by the unintentional comment that was started in
the line

a = b/*p;

That "/*" is all it takes.  That can be really mean to catch.  The moral
of the story is not to be afraid to use spaces (You may also want to hope
modifications are added to detect "/*" inside "comments".)

					Mike Laman
					sdcsvax!laman

davec (01/04/83)

Concerning the earlier problem posed to the net:
	------------------------
 	This is a (fairly) simple puzzle.
   	Why does this program print "1" instead of "2"?
   	Note: (1/1)+1 == 2 not 1
	*/

	main()
	{
	int a,b,*p;
		b= 1;
		p= &b;
		a= b/*p;
		++a /* oh? */;
		printf("%d\n",a);
	}

	/*
	--dmy--
	*/

	----------------

No doubt your compiler will interpret

		a= b/*p;
		++a /* oh? */;

as 		a= b	/* COMMENT */;

since the "/*" following the b will be taken as the beginning of
a comment string which ends with the "*/" following "oh? ", thus
never performing your intended division by *p, nor incrementing
"a" on the next line. Your program thus would execute as:

		b= 1;
		p= &b;
		a= b;
		printf("%d\n",a);

resulting with "1" being printed, not "2". A quick solution to this
is to change the line with the division to

		a= b/(*p);

and all will work as you intended. A better solution is to leave
spaces between your binary operators and their operands, such as

		a = b / *p;

which is much easier to read anyway, and avoids these types of
bugs.

Dave Cobbley
Tektronix, Inc.