home *** CD-ROM | disk | FTP | other *** search
/ High Voltage Shareware / high1.zip / high1 / DIR9 / WDOS0793.ZIP / ZOLMAN.ZIP / VFORMAT.C < prev    next >
C/C++ Source or Header  |  1993-05-12  |  2KB  |  59 lines

  1. /*
  2.  * vformat.c:
  3.  *  Illustrates John N. Power's technique of passing variable format
  4.  *  strings and variable data-type parameters in printf() calls.
  5.  * 
  6.  * Compile & Link (Borland C):
  7.  *  bcc vformat.c
  8.  */
  9.  
  10. #include    "stdio.h"
  11.  
  12. #define     REAL    0
  13. #define     INTEGER 1
  14. #define     ERROR   2
  15.  
  16. char *fill[] = {"          ",
  17.         " ........ " };
  18.  
  19. union number {
  20.     double real;  /* <- Must use a double, not a float, since printf  */
  21.     int fix;      /*      expects floats to be promoted when passed.  */
  22. } sample;
  23.  
  24. void outnum(int type, union number *parm);
  25.  
  26. main()
  27. {
  28.     int i;
  29.  
  30.     for(i=1;i<11;i++){
  31.         sample.fix = i;
  32.         outnum(INTEGER, &sample);
  33.         printf(*(fill + ((i % 3) == 0)));
  34.         sample.real = sample.fix;  /* <- implied type conversion */
  35.         outnum(REAL, &sample);
  36.     }
  37.     return 0;
  38. }
  39.  
  40. char *format[] = {      "%5.2f\n",
  41.             "%5d",
  42.             "*ERR*" };
  43.  
  44. void outnum(int type, union number *parm)
  45. {
  46.     if ((type != REAL) && (type != INTEGER))
  47.         type = ERROR;
  48.     printf(*(format + type), *parm);
  49.  
  50.     /* Pass the entire union by value.  Let printf figure
  51.     out how much of it to use.  This union must be the last
  52.     variable passed to printf, since printf determines the
  53.     locations of its parameters from the lengths of the parameters,
  54.     as indicated by the fields in the format string.  Since not
  55.     all of the union may be used, placing the union anywhere but
  56.     at the end will cause printf to mislocate the following
  57.     variables.    */
  58. }
  59.