home *** CD-ROM | disk | FTP | other *** search
/ C by Discovery (4th Edition) / C_By_Discovery_4th_Edition.tar / C_By_Discovery_4th_Edition / _DISK_ / ch11 / macros.c < prev    next >
C/C++ Source or Header  |  2005-06-16  |  2KB  |  64 lines

  1. /*               macros.c
  2.  *
  3.  *   Synopsis  - Accepts input of two integers from the keyboard 
  4.  *               and displays the maximum of the two values.
  5.  *
  6.  *   Objective - Will illustrate the expansion of macros by the
  7.  *               preprocessor.
  8.  */
  9.  
  10. /* Include Files */
  11. #include <stdio.h>                                /* Note 1 */
  12. #include <ctype.h>                                /* Note 2 */
  13.  
  14. /* Macro Definitions */
  15. #define MAX(a, b)          (a > b) ? a : b        /* Note 3 */
  16.  
  17. /* Function Prototypes */
  18. int getint( int *val );
  19. /*   PRECONDITION: val contains the address of an int
  20.  *
  21.  *   POSTCONDITION: Reads a line of input and converts input digits to 
  22.  *                  a value of type int and stores the result in its 
  23.  *                  parameter; returns a 0 for success and a 1 if any 
  24.  *                  nondigit is found; in the latter case, the 
  25.  *                  contents of val are set to 0
  26.  */
  27.  
  28. int main( void )
  29. {
  30.      int x, y;
  31.  
  32.      printf( "Calculating the maximum of two numbers.\n" );
  33.      printf( "Please enter the first nonnegative number : " );
  34.      getint( &x );
  35.      printf( "Please enter the second nonnegative number : " );
  36.      getint( &y );
  37.      printf( "The maximum of %d and %d is %d.\n",x, y, MAX( x,y ));
  38.                                                    /* Note 4 */
  39.      return 0;
  40. }
  41.  
  42. /*******************************getint()************************/
  43.  
  44. int getint( int *val )
  45. {
  46.      int iochar, num;
  47.  
  48.      num = 0;
  49.      while (( iochar = getchar() ) != '\n' ) {     /* Note 5 */
  50.           if ( isdigit( iochar ))                  /* Note 6 */
  51.                num = 10*num + iochar - '0';
  52.           else {
  53.                printf( "Illegal input - %c\n", iochar );
  54.                                                    /* Note 7 */
  55.                while (( iochar = getchar() ) != '\n' )
  56.                ;
  57.                *val = 0;
  58.                return( 1 );
  59.           }
  60.      }
  61.      *val = num;
  62.      return ( 0 );
  63. }
  64.