Defining Macros with Parameters - PowerPoint PPT Presentation

About This Presentation
Title:

Defining Macros with Parameters

Description:

To extend a macro over multiple lines, all except for the last line must end ... Operators with side effect should not be used as macro arguments. ... – PowerPoint PPT presentation

Number of Views:234
Avg rating:3.0/5.0
Slides: 7
Provided by: RPy1
Category:

less

Transcript and Presenter's Notes

Title: Defining Macros with Parameters


1
Defining Macros with Parameters
  • Defining constant macro
  • define macro_name value
  • For example
  • define KMS_PER_MILE 1.609
  • Defining macro with parameters
  • define macro_name(parameter lis) macro body
  • For example
  • define SQUARE(n) ((n) (n))

2
Program Using a Macro with Parameters
  • / Shows the definition and use of a macro /
  • include ltstdio.hgt
  • define LABEL_PRINT_INT(label, num) \
  • printf("s d",
    (label), (num))
  • int
  • main(void)
  • int r 5, t 12
  • LABEL_PRINT_INT("rabbit", r)
  • printf(" ")
  • LABEL_PRINT_INT("tiger", t 2)
  • printf("\n")
  • return(0)
  • rabbit 5 tiger 14

3
Macro Expansion
  • LABEL_PRINT_INT(tiger, t2) Second macro
    call in the main
  • LABEL_PRINT_INT(label, num)
  • Parameter matching tiger t2
  • printf(s d, (label), (num))
  • parameter replacement in body
  • printf(s d, (tiger), (t2))

4
Rules for Defining Macros with parameters
  • Same as constant macro there is no at the end
    of macro definition
  • To extend a macro over multiple lines, all except
    for the last line must end with backslash
    character /
  • Operators with side effect should not be used as
    macro arguments.
  • For example define RT(a) is wrong

5
Rules for Defining Macros with parameters
  • Using the parenthesis for the formal parameters
    in Macro body is required to avoid the effect of
    operator precedence in macro expansion. For
    example
  • Version 1 Version 2
  • define SQUARE(n) n n define SQUARE(n)
    ((n) (n))
  • SQUARE(x y)
    SQUARE(x y)
  • becomes becomes
  • x y x y ((x
    y) (x y))
  • Problem multiplication done before addition
    in version 1, also.
  • SQUARE(m) / SQUARE(n) SQUARE(m) /
    SQUARE(n)
  • becomes becomes
  • m m / n n ((m)
    (m)) / ((n) (n))
  • Therefore, the result produced by version 1 is
    wrong

6
More examples of Macro with Parameters
  • define ROOT1(a, b, c) \
  • ((-(b) sqrt((b) (b) 4 (a) (c))) / (2
    (a)))
  • Can be used in the main as
  • r ROOT1(n1, n2, n3)
  • define INDEXED-FOR(ct, st, end) \
  • for ((ct) (st) (ct) lt (end) (ct))
  • Can be used in the main as
  • INDEXED_FOR(i,0,X_MAX)
  • printf(x2d 6.2f\n, i, xi)
Write a Comment
User Comments (0)
About PowerShow.com