[comp.lang.c] #define thisneatmacro

otto@tukki.jyu.fi (Otto J. Makela) (10/19/90)

In article <9286@helios.TAMU.EDU> ctl8588@rigel.tamu.edu (LAUGHLIN, CHET)
writes:
	[how to convert function to macro ?]
   I tried useing the following macro, with some success...
   #define drawch(A,B,C)  {gotoxy(A,B); cput(C);}
   however, the following code won't work...compiler doesn't like
   the extra ; at the end of drawch...
   if (cond)
      drawch(x,y,ch);
   else
      printf("ICK!\n");

The classic solution (which perhaps should go into the FAQ posting) is to do:
#define	drawch(A,B,C)	do { gotoxy(A,B); cput(C); } while(0)
which makes the macro work correctly inside if's.  A good optimizing compiler
will remove the extra caused by 'do {} while(0)'

Of course, one thing you could also do is
#define	drawch(A,B,C)	( gotoxy(A,B), cput(C) )
(remember, a comma is the discard-value-of-1st-argument-return-value-of-2nd
operator if outside function evocations).  This is a bit more risky, however,
since things could get hairy if gotoxy or cput are also macros.

This will undoubtedly be the main topic in this newsgroup for the next three
weeks, as everyone will post their favorite answer as in the count-the-bits
and the hash function problems.
--
   /* * * Otto J. Makela <otto@jyu.fi> * * * * * * * * * * * * * * * * * * */
  /* Phone: +358 41 613 847, BBS: +358 41 211 562 (CCITT, Bell 24/12/300) */
 /* Mail: Kauppakatu 1 B 18, SF-40100 Jyvaskyla, Finland, EUROPE         */
/* * * Computers Rule 01001111 01001011 * * * * * * * * * * * * * * * * */