Thinking in C and *nix (CSC 282 2015S) : EBoards
Primary: [Front Door] [Schedule] - [Academic Honesty] [Disabilities] [Email] [FAQ] [Teaching & Learning] - [Calendar]
Current: [Outline] [EBoard] [Lab] [Assignment]
Sections: [Assignments] [EBoards] [Examples] [Handouts] [Labs] [Outlines]
Reference: [EBook] - [ISO] [GNU Coding Standards] [GCC Documentation] - [TAoUP] [Make3]
Previous Offerings: [CSC 295 2013S] [CSC 295 2014S]
Misc: [SamR] [Glimmer Labs] [CS@Grinnell] [Grinnell] [Issue Tracker]
Overview
Examples (defining a single value):
#define ARRAY_SIZE 1000
int values[ARRAY_SIZE];
Examples (defining something function-like)
#define SQUARE(X) X*X
printf("%d squared is %d\n", i, SQUARE(i));
Why use #define rather than constant?
swap. printf("%d\n", SQUARE(2+3));
int x = 3;
printf("%d\n", SQUARE(x++);
printf("x= %d\n", x);
We should have defined it as
#define SQUARE(X) ((X)*(X))
Solving with Macros
Strategy 1
#define LOG(message) printf("%s\n", message);
#define LOG(message)
A cool thing you can do with modern macros (e.g., in GNU CC)
#PARAM gives you a parameter as a string
Strategy 2
#ifdef DEBUG
#define LOG(message) fprintf(stderr, "*** %s ***\n", message);
#define LOGI(i) fprintf(stderr, " *** %s = %d ***\n", #i, i);
#else
#define LOG(message)
#define LOGI(i)
#endif
PARAM ## text
substitutes and then concatenates.