Page 94 - C-Language
P. 94
#include <stdio.h>
int main(void) {
int array[3] = {1,2,3}; // 4 bytes * 3 allocated
unsigned char *ptr = (unsigned char *) array; // unsigned chars only take 1 byte
/*
* Now any pointer arithmetic on ptr will match
* bytes in memory. ptr can be treated like it
* was declared as: unsigned char ptr[12];
*/
return 0;
}
Macros are simple string replacements
Macros are simple string replacements. (Strictly speaking, they work with preprocessing tokens,
not arbitrary strings.)
#include <stdio.h>
#define SQUARE(x) x*x
int main(void) {
printf("%d\n", SQUARE(1+2));
return 0;
}
You may expect this code to print 9 (3*3), but actually 5 will be printed because the macro will be
expanded to 1+2*1+2.
You should wrap the arguments and the whole macro expression in parentheses to avoid this
problem.
#include <stdio.h>
#define SQUARE(x) ((x)*(x))
int main(void) {
printf("%d\n", SQUARE(1+2));
return 0;
}
Another problem is that the arguments of a macro are not guaranteed to be evaluated once; they
may not be evaluated at all, or may be evaluated multiple times.
#include <stdio.h>
#define MIN(x, y) ((x) <= (y) ? (x) : (y))
int main(void) {
int a = 0;
printf("%d\n", MIN(a++, 10));
printf("a = %d\n", a);
return 0;
https://riptutorial.com/ 70

