Skip to content

Commit 4c014da

Browse files
committed
[sieve example] Add quiet option to suppress printing
1 parent 8a4c5fe commit 4c014da

File tree

1 file changed

+20
-13
lines changed

1 file changed

+20
-13
lines changed

examples/sieve.c

Lines changed: 20 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -35,17 +35,20 @@ static void print_input_error_and_exit(void) {
3535
}
3636

3737
int main(int argc, char **argv) {
38-
if (argc != 2) {
39-
printf("usage: %s <n>\n", argv[0]);
38+
if (argc < 2 || argc > 3) {
39+
printf("usage: %s [-q] <n>\n", argv[0]);
4040
exit(1);
4141
}
4242

43-
if (!sanitise_input_number(argv[1])) {
43+
size_t n_idx = argc == 2 ? 1 : 2;
44+
bool quiet = argc == 3 && strcmp(argv[1], "-q") == 0;
45+
46+
if (!sanitise_input_number(argv[n_idx])) {
4447
print_input_error_and_exit();
4548
}
4649

4750
errno = 0;
48-
long int result = strtol(argv[1], NULL, 10 /* base 10 */);
51+
long int result = strtol(argv[n_idx], NULL, 10 /* base 10 */);
4952
if (result <= 0 && (errno == ERANGE || errno == EINVAL || result > MAX_PRIMES_LIMIT)) {
5053
print_input_error_and_exit();
5154
}
@@ -65,14 +68,16 @@ int main(int argc, char **argv) {
6568
if (divisible) break;
6669
}
6770
if (!divisible) {
68-
char sbuf[11]; // 10 digits + null character.
69-
int32_t len = snprintf(sbuf, sizeof(sbuf), "%" PRId32 " ", i);
70-
if (len < 1) {
71-
fprintf(stderr, "error: failed to convert int32_t to a string\n");
72-
abort();
73-
}
74-
for (int32_t i = 0; i < len; i++) {
75-
putc(sbuf[i], stdout);
71+
if (!quiet) {
72+
char sbuf[11]; // 10 digits + null character.
73+
int32_t len = snprintf(sbuf, sizeof(sbuf), "%" PRId32 " ", i);
74+
if (len < 1) {
75+
fprintf(stderr, "error: failed to convert int32_t to a string\n");
76+
abort();
77+
}
78+
for (int32_t i = 0; i < len; i++) {
79+
putc(sbuf[i], stdout);
80+
}
7681
}
7782
fiber_t filter_fiber = fiber_alloc((fiber_entry_point_t)(void*)filter);
7883
(void)fiber_resume(filter_fiber, (void*)(intptr_t)i, &status);
@@ -81,7 +86,9 @@ int main(int argc, char **argv) {
8186
}
8287
i++;
8388
}
84-
putc('\n', stdout);
89+
if (!quiet) {
90+
putc('\n', stdout);
91+
}
8592

8693
assert(p == max_primes);
8794
// Clean up

0 commit comments

Comments
 (0)