4 ms·
I realize it's not quite your point, but if you don't like repeating yourself, macros and "statement expressions" make it simple to extend languages to capture
by nkurz 11y ago
I realize it's not quite your point, but if you don't like repeating yourself, macros and "statement expressions" make it simple to extend languages to capture "it" to a tmp variable and then reuse it:
#include <stdlib.h>
#include <stdio.h>
#define dry(x, test, if_true, if_false) ({ \
typeof(x) _x = (x); \
(_x test) ? if_true(_x) : if_false(_x); \
})
#define abs(x) dry(x, < 0, -, )
int main(int argc, char **argv) {
if (argc == 1) printf("usage: %s num [num]...", argv[0]);
for (int i = 1; i < argc; i++) {
char *string = argv[i];
int num = atoi(string);
printf("string '%s', num %d, abs %d\n",
string, num, abs(num));
}
return 0;
}
$ gcc -std=gnu99 -Wall -Wextra -O3 -g dry.c -o dry
$ dry 2 1 0 -1 -2
string '2', num 2, abs 2
string '1', num 1, abs 1
string '0', num 0, abs 0
string '-1', num -1, abs 1
string '-2', num -2, abs 2