Presentation is loading. Please wait.

Presentation is loading. Please wait.

ECE 103 Engineering Programming Chapter 37 C Macro Parameters

Similar presentations


Presentation on theme: "ECE 103 Engineering Programming Chapter 37 C Macro Parameters"— Presentation transcript:

1 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 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
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


Download ppt "ECE 103 Engineering Programming Chapter 37 C Macro Parameters"

Similar presentations


Ads by Google