I want to be able to do something like this:
while (line = fgets(line, n, input)) {
if (strlen(line) == 1)
print_and_continue("Blank line.\n");
printf("%s\n", line);
}
Ordinarily the way to do this and cover all syntactic intricacies is to employ a freakish do while(0)
loop:
#define print_and_die(x) do {printf("%s\n", (x)); exit(1);} while (0)
However, I can't use continue
(or break
for that matter) in place of exit(1)
cause it would apply to the do while(0)
loop, not the loop I want it. And sure, I can just define the macro like:
#define print_and_continue(x) {printf("%s\n", (x)); continue;}
And expect the user not to write code like this:
if (something)
print_and_continue(x);
else {...}
But I want to know, is there a way to cover all syntactic cases?
There has been a slight debate in comments as to whether construct this construct is useful enough that it warrants avoiding outright writing:
if (condition) {
printf("Failure.\n");
continue;
}
Just to illustrate the point, if there are a lot of conditions that make you want to skip processing data (or even partially process data before skipping it) then yes, it very much becomes useful.
Compare the readability of the two. The latter is rather repetitive and unreadable (and trickier to edit)
/* With print_and_continue() */
char buffer[BUFSIZ];
while (fgets(buffer, sizeof(buffer), input)) {
if (strlen(buffer) < 10)
print_and_continue("To small.");
if (strlen(buffer) > 100)
print_and_continue("To large.");
if (strcmp(buffer, "Do not print this"))
print_and_continue("Avoided printing a line.");
fputs(buffer, output);
}
/* Without print_and_continue() */
char buffer[BUFSIZ];
while (fgets(buffer, sizeof(buffer), input)) {
if (strlen(buffer) < 10){
printf("Too small.\n");
continue;
}
if (strlen(buffer) > 100) {
printf("To large.\n");
continue;
}
if (strcmp(buffer, "Do not print this")) {
printf("Avoided printing a line.\n");
continue;
}
fputs(buffer, output);
}