Simple C Puzzle

utzoo!decvax!duke!harpo!seismo!hao!menlo70!sytek!zehntel!tektronix!tekmdp!bronze!davec utzoo!decvax!duke!harpo!seismo!hao!menlo70!sytek!zehntel!tektronix!tekmdp!bronze!davec
Tue Jan 4 09:19:50 AEST 1983


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.



More information about the Comp.lang.c mailing list