F.10. Wrap-Up

Answers to Self Review Exercises

F.1

a) #. b) #elif, #else. c) #define. d) white space. e) #undef. f) #ifdef, #ifndef. g) Conditional compilation. h) assert. i) #include. j) ##. k) #. l) .

F.2

(See below.)

 1 // exF_02.cpp
 2 // Self-Review Exercise F.2 solution.
 3 #include 
 4
 5 using std::cout;
 6 using std::endl;
 7
 8 int main()
 9 {
10 cout << "__LINE__ = " << __LINE__ << endl
11 << "__FILE__ = " << __FILE__ << endl
12 << "__DATE__ = " << __DATE__ << endl
13 << "__TIME__ = " << __TIME__ << endl
14 << "__cplusplus = " << __cplusplus << endl;
15
16 return 0;
17
18 } // end main
 
 __LINE__ = 9
 __FILE__ = c:cpp4ech19ex19_02.CPP
 __DATE__ = Jul 17 2002
 __TIME__ = 09:55:58
 __cplusplus = 199711L
 
F.3
  1. #define YES 1
  2. #define NO 0
  3. #include "common.h"
  4. #if defined(TRUE) #undef TRUE #define TRUE 1 #endif
  5. #ifdef TRUE #undef TRUE #define TRUE 1 #endif
  6. #if ACTIVE #define INACTIVE 0 #else #define INACTIVE 1 #endif
  7. #define CUBE_VOLUME( x ) ( ( x ) * ( x ) * ( x ) )

Exercises

F.4

Write a program that defines a macro with one argument to compute the volume of a sphere. The program should compute the volume for spheres of radii from 1 to 10 and print the results in tabular format. The formula for the volume of a sphere is

( 4.0 / 3 ) * p * r3
 

where p is 3.14159.

F.5

Write a program that produces the following output:

 The sum of x and y is 13
 
 

The program should define macro SUM with two arguments, x and y, and use SUM to produce the output.

F.6

Write a program that uses macro MINIMUM2 to determine the smaller of two numeric values. Input the values from the keyboard.

F.7

Write a program that uses macro MINIMUM3 to determine the smallest of three numeric values. Macro MINIMUM3 should use macro MINIMUM2 defined in Exercise F.6 to determine the smallest number. Input the values from the keyboard.

F.8

Write a program that uses macro PRINT to print a string value.

F.9

Write a program that uses macro PRINTARRAY to print an array of integers. The macro should receive the array and the number of elements in the array as arguments.

 
F.10

Write a program that uses macro SUMARRAY to sum the values in a numeric array. The macro should receive the array and the number of elements in the array as arguments.

F.11

Rewrite the solutions to Exercise F.4 to Exercise F.10 as inline functions.

F.12

For each of the following macros, identify the possible problems (if any) when the preprocessor expands the macros:

  1. #define SQR( x ) x * x
  2. #define SQR( x ) ( x * x )
  3. #define SQR( x ) ( x ) * ( x )
  4. #define SQR( x ) ( ( x ) * ( x ) )




C++ How to Program
C++ How to Program (5th Edition)
ISBN: 0131857576
EAN: 2147483647
Year: 2004
Pages: 627
Simiral book on Amazon

Flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net