Browse Source

add new example for designated initializers (ch. 10)

master
T. Meissner 10 years ago
parent
commit
466ac5fbde
2 changed files with 74 additions and 2 deletions
  1. +5
    -2
      21st_century_c/Makefile
  2. +69
    -0
      21st_century_c/boxes.c

+ 5
- 2
21st_century_c/Makefile View File

@ -1,17 +1,20 @@
CFLAGS = --std=c11 -Wall -O3
boxes : boxes.c
$(CC) $(CFLAGS) $@.c -o $@
show_tree : process_dir.h process_dir.c show_tree.c
$(CC) $(CFLAGS) process_dir.c $@.c -o $@
simple_cplx : cplx.h complex.c simple_cplx.c
$(CC) `pkg-config --cflags --libs gsl` $(CFLAGS) complex.c $@.c -o $@
.PHONY : all
all : show_tree simple_cplx
all : boxes show_tree simple_cplx
.PHONY : clean
clean :
rm -f boxes
rm -f show_tree
rm -f simple_cplx

+ 69
- 0
21st_century_c/boxes.c View File

@ -0,0 +1,69 @@
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
typedef struct {
char *name;
int left, right, up, down;
} direction_s;
void this_row(direction_s d);
void draw_box(direction_s d);
int main() {
direction_s D = {.name = "left", .left = 1};
draw_box(D);
// name is first, so we can omit label
D = (direction_s) {"upper right", .up = 1, .right = 1};
draw_box(D);
// all struct elements set to zero
draw_box((direction_s){});
}
void this_row(direction_s d) {
char s[] = ".*.\n";
if(d.left) {
strlcpy(s, "*..\n", sizeof(s));
} else if(d.right) {
strlcpy(s, "..*\n", sizeof(s));
}
printf("%s", s);
}
void draw_box(direction_s d) {
printf("%s:\n", (d.name ? d.name : "a box"));
if(d.up) {
this_row(d);
} else {
printf("...\n");
}
if(!d.up && !d.down) {
this_row(d);
} else {
printf("...\n");
}
if(d.down) {
this_row(d);
} else {
printf("...\n");
}
printf("\n");
}

Loading…
Cancel
Save