home *** CD-ROM | disk | FTP | other *** search
/ NetNews Usenet Archive 1992 #19 / NN_1992_19.iso / spool / comp / lang / c / 12922 < prev    next >
Encoding:
Text File  |  1992-08-29  |  2.1 KB  |  54 lines

  1. Path: sparky!uunet!caen!rphroy!einstein!wenner
  2. From: wenner@einstein.eds.com (Rich Wenner)
  3. Newsgroups: comp.lang.c
  4. Subject: Re: printf question
  5. Message-ID: <1226@pascal.einstein.eds.com>
  6. Date: 28 Aug 92 18:09:32 GMT
  7. References: <1992Aug27.143434.26965@dartvax.dartmouth.edu> <kimcm.714943581@login.dkuug.dk>
  8. Organization: Electronic Data Systems
  9. Lines: 43
  10.  
  11. In article <kimcm.714943581@login.dkuug.dk> kimcm@login.dkuug.dk (Kim Chr. Madsen) writes:
  12. >eht@coos.dartmouth.edu (Edward H. Truex) writes:
  13. >
  14. >>I am trying to format a hexadecimal number whose width 
  15. >>is always a constant - like 
  16. >
  17. >>    printf("%04x\n", address );
  18. >
  19. >try to use the variable width specification method:
  20. >
  21. >    printf("%0*x\n",4, adress);
  22. >
  23. >an asteriks in the width specification is taken as a variable that
  24. >must be taken from the arguments and be evaluated at runtime...
  25.  
  26. The above will work just fine, but if you have a full ANSI compiler, the
  27. syntax ...
  28.  
  29. #define HDPI "4" /* Hex Digits Per Int */
  30.  
  31.     printf( "%0" HDPI "x\n", address );
  32.  
  33. ... will also work, provided that your constant is defined as a character
  34. string literal.  The ANSI preprocessor will see character string literals
  35. with no intervening symbols other than whitespace, and will concatenate
  36. them into a single string.  This is the same trick you can use for ...
  37.  
  38.     fputs( "This is a really long message to write out to a file, but "
  39.         "now, thanks to ANSI, I don't have to do that hokey crap "
  40.         "of putting backslashes in awkward places or doing a bunch "
  41.         "of strcats.", file_ptr );
  42.  
  43. And if you have read this far, you surely won't mind one more irrelevant
  44. remark ;-)  Using this syntax on the original problem will save you some
  45. time because the format is evaluated at compile time instead of run time.
  46. Depending on your hardware platform, this may actually amount to several
  47. nanoseconds!
  48.  
  49. -- 
  50. Rich Wenner               | It is by the goodness of God that in our country we
  51. wenner@pascal.tsd.eds.com | have those 3 unspeakably precious things:  freedom
  52.                           | of speech, freedom of conscience, and the prudence
  53. #include <stddisclaimer.h>| never to practice either of them.      Mark Twain
  54.