1 / 7

ECE 103 Engineering Programming Chapter 37 C Macro Parameters

ECE 103 Engineering Programming Chapter 37 C Macro Parameters. Herbert G. Mayer, PSU CS Status 6/4/2014 Initial content copied verbatim from ECE 103 material developed by Professor Phillip Wong @ PSU ECE. Syllabus. Defining a Parameterized Macro Parameterized Macros vs. C Functions.

Download Presentation

ECE 103 Engineering Programming Chapter 37 C Macro Parameters

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. ECE 103 Engineering ProgrammingChapter 37C Macro Parameters Herbert G. Mayer, PSU CS Status 6/4/2014 Initial content copied verbatim from ECE 103 material developed by Professor Phillip Wong @ PSU ECE

  2. Syllabus • Defining a Parameterized Macro • Parameterized Macros vs. C Functions

  3. Defining a Parameterized Macro Similar to a C function, preprocessor macros can be defined with a parameter list. The macro’s parameters do not require data types to be specified. Syntax: #define MACRONAME(parameter_list) text No white space is allowed between the name of the macro and the left parenthesis. 2

  4. Parameters in the parameter_list are separated by commas. Example: #define MAXVAL(A,B) ((A) > (B)) ? (A) : (B) #define PRINT(e1,e2) printf(”%c\t%d\n”,(e1),(e2)); #define putchar(x) putc(x, stdout) Arguments passed to the parameterized macro are substituted verbatim into the corresponding parameters. 3

  5. Care must be taken to avoid side-effects. Use parentheses to force a particular interpretation. Example: /* This has potential side-effects */ #define PROD1(A,B) A * B PROD1(1+3,2) → 1+3 * 2 /* Use parentheses as needed */ #define PROD2(A,B) (A) * (B) PROD2(1+3,2) → (1+3) * (2) 4

  6. Example: #include <stdio.h> #include <math.h> #define EVERYFIFTH(n) ((n) %5 == 0) int main (void) { int k; for (k = 0; k < 100; k++) if (EVERYFIFTH(k)) /* Silly, but it does work */ printf("%3d %.3f\n", k, sqrt(k)); return 0; } 5

  7. Parameterized Macros vs. C Functions Since macro expansion is done at compile-time, there is no function call overhead at runtime. There is no type checking performed for macros, which is useful if generic data types are desired for arguments. Unlike a C function, parameterized macros have no concept of local variables. 6

More Related