Advertisement
cd62131

print array with _Generic

Nov 30th, 2018
595
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.26 KB | None | 0 0
  1. #include <stdio.h>
  2. static void print_array_char(char *, size_t);
  3. static void print_array_int(int *, size_t);
  4. static void print_array_unsigned(unsigned *, size_t);
  5. static void print_array_char(char *a, size_t n) {
  6.     printf("[");
  7.     for (size_t i = 0; i < n; ++i) {
  8.         printf("%s%c", ((i == 0) ? "" : ", "), a[i]);
  9.     }
  10.     puts("]");
  11. }
  12. static void print_array_int(int *a, size_t n) {
  13.     printf("[");
  14.     for (size_t i = 0; i < n; ++i) {
  15.         printf("%s%d", ((i == 0) ? "" : ", "), a[i]);
  16.     }
  17.     puts("]");
  18. }
  19. static void print_array_unsigned(unsigned *a, size_t n) {
  20.     printf("[");
  21.     for (size_t i = 0; i < n; ++i) {
  22.         printf("%s%d", ((i == 0) ? "" : ", "), a[i]);
  23.     }
  24.     puts("]");
  25. }
  26. #define print_array(a, n) _Generic((a) \
  27.         , char *: print_array_char \
  28.         , int *: print_array_int \
  29.         , unsigned *: print_array_unsigned \
  30.         )(a, n)
  31. int main(void) {
  32.     char array_char[] = { 'h', 'e', 'l', 'l', 'o' };
  33.     int array_int[] = { -2, -1, 1, -2 };
  34.     unsigned array_uint[] = { 1, 2, 3 };
  35.     print_array(array_char, sizeof array_char / sizeof array_char[0]);
  36.     print_array(array_int, sizeof array_int / sizeof array_int[0]);
  37.     print_array(array_uint, sizeof array_uint / sizeof array_uint[0]);
  38. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement