More to come...
選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。

192 行
13KB

  1. #ifndef CHAPTER_3_SOURCE
  2. #define CHAPTER_3_SOURCE
  3. #include <stddef.h>
  4. #include <stdarg.h>
  5. #include "chapter_3.h"
  6. /*
  7. This is probably a good time to show you how switch statement works, and two (in my opinion best) ways to align them, but I advise against mixing two alignments you'll see in
  8. 'print_colour' and 'print_format' functions. Also, it's a good practice to always use 'default' keyword at the end of you switch statements. You don't always need to use 'break'
  9. at the end of 'case', but we intend to "end" the switch statement there, so it's fine. Cases can be "fall-through", so if you don't put 'break', it'll execute the code in the next
  10. one, or you could have several of cases before any code. I don't like to use them like that, but here are few examples:
  11. @C
  12. // If argument 'character' is any of the uppercase letters, it returns TRUE, if lowercase, it returns FALSE, otherwise exits the program.
  13. static bool hexadecimal_letter_is_uppercase (char character)
  14. switch (character) {
  15. case 'A': case 'B': case 'C': case 'D': case 'E': case 'F': return (TRUE); // We don't need to break here, because these two return from function.
  16. case 'a': case 'b': case 'c': case 'd': case 'e': case 'f': return (FALSE); // If there was code after the switch statement, we would use 'break' keyword.
  17. default: exit (EXIT_FAILURE); // We don't need to break here yet again, because we exit a program!
  18. }
  19. }
  20. @
  21. You can use only integers in cases, and remember, 'char' is implicitly promoted to 'int', aka integer. And important thing to keep in mind is that you can write every switch
  22. statement as if-else statement, but it would be longer, more error-prone, some lines of code would repeat, and many more inconveniences would come, especially because in C, cases
  23. can fall-through, like in the example below. Sad truth is, people are dumb, and many compilers and linters will output a warning message complaining that you used fall-through
  24. case(s) in your switch statement. Lets explain what 'echo_one_by_one' function would do.
  25. @C
  26. static void echo_one_by_one (int number) {
  27. switch (number) {
  28. case 0: echo ("Zero ");
  29. case 1: echo ("One ");
  30. case 2: echo ("Two ");
  31. case 3: echo ("Three ");
  32. default: break;
  33. }
  34. }
  35. // Print out some stuff, it'll look like this for these inputs (and it'll do nothing for input that isn't between 0 and 3 (inclusive)):
  36. // echo_one_by_one (0) => "Zero One Two Three"
  37. // echo_one_by_one (1) => "One Two Three"
  38. // echo_one_by_one (2) => "Two Three"
  39. // echo_one_by_one (3) => "Three"
  40. @
  41. You can find situations in which fall-through cases are good, for example, they can be very useful when encoding some CPU instructions into machine code, but guess what? The
  42. compiler will think you've made some kind of mistake, like that you forgot to break from those cases, and it'll warn you about it. I like to clean all compiler warnings (and some
  43. linter warnings, if they're not totally brain-dead), so I just don't use them. I know, sounds stupid, but there's usually some other way to do it, to get the same solution. Since
  44. we have several methods for printing text, they use standard output (terminal), file descriptor and a string respectively, we could implement them in separate functions, use
  45. function pointers or simply copy+paste bunch of code into lot of functions, and form a "function family". Lets do something very simple and straight forward. We'll end up with
  46. repeated code, but sometimes the simplicity can benefit us more than some smart solutions that are harder to understand. I'll explain as we progress...
  47. */
  48. static void to_output (char * data, int size, int file, char * string) { (void) file; (void) string; out ( data, size); }
  49. static void to_file (char * data, int size, int file, char * string) { (void) string; file_write (file, data, size); }
  50. static void to_string (char * data, int size, int file, char * string) { (void) file; string_concatenate_limit (string, data, size); }
  51. /*
  52. Lets break down what's going on here, since it might be confusing for beginners. We've defined 3 internal functions, that'll only be used in this file and no other. They look
  53. similar, and they ignore some of their arguments by casting them to 'void', that's how you silence the compiler warnings about unused function agruments. But why are we passing
  54. those arguments if we won't use them? Because we can safely use one function pointer to any of those 3 functions. Now, before we proceed, variables can hold memory addresses of
  55. other variables, constants and functions. We use that fact now.
  56. Internal variable 'printing' is a function pointer to one of those 3 functions, and the default value for it is the memory address of function 'to_output'. So, if we just use it,
  57. by default it'll print to standard output. If we call functions below, they'll change the value of 'printing' to coresponding function memory address. I chose to use concatenation
  58. for 'print_string', but if you wanted, you could use something else, or just reinitialize it to null string, and think about memory before using it. Unlike 'printf' function from
  59. <stdio.h> header file, my print functions don't allocate memory or make buffers.
  60. */
  61. static void (* printing) (char * data, int size, int file, char * string) = to_output;
  62. static void print_colour (char colour_id, int file, char * string) {
  63. switch (colour_id) { // We use "special" character '/' to use terminal colours.
  64. case '/': (* printing) ("/", 1, file, string); break; // If we have literally typed "//" in our 'format' string, it'll just output "/".
  65. case '0': (* printing) ("\033[1;30m", 7, file, string); break; // Notice that we couldn't use function 'terminal_colour', it only uses standard output.
  66. case '1': (* printing) ("\033[1;31m", 7, file, string); break; // Since we want to support file descriptors and strings, we use 'printing'.
  67. case '2': (* printing) ("\033[1;32m", 7, file, string); break; // Also, we're dereferencing 'printing' pointer, which essentially calls one of the 3 functions.
  68. case '3': (* printing) ("\033[1;33m", 7, file, string); break;
  69. case '4': (* printing) ("\033[1;34m", 7, file, string); break;
  70. case '5': (* printing) ("\033[1;35m", 7, file, string); break;
  71. case '6': (* printing) ("\033[1;36m", 7, file, string); break;
  72. case '7': (* printing) ("\033[1;37m", 7, file, string); break;
  73. case '-': (* printing) ("\033[0m", 4, file, string); break;
  74. default: (* printing) ("?", 1, file, string); break; // Now, if we provided some other character after "/", I like to make an intentional mismatch.
  75. } // It's not such a big mistake to abort the program, since it's obvious that results are bad.
  76. }
  77. static void print_format (char format_id, va_list list, int file, char * string) {
  78. switch (format_id) { // We use character '%' this time, same as 'printf' function does, lets see...
  79. case '%': {
  80. (* printing) ("%", 1, file, string);
  81. } break;
  82. case 'i': {
  83. int integer; // Leave these local variables uninitialized (don't assign a value to them).
  84. char * format; // We'll use format here and below in order to shorten the length of lines.
  85. integer = va_arg (list, int); // Macro 'va_arg' will pop an argument from the list, with the provided type.
  86. format = number_to_string (integer);
  87. (* printing) (format, string_length (format), file, string); // You might get the feeling that this isn't type safe, and you're totally right.
  88. } break;
  89. case 'f': {
  90. double ieee754; // Because we used curly braces, we can declare local variables in these blocks of code.
  91. char * format;
  92. ieee754 = va_arg (list, double); // I intentionally call this IEEE754 because I hate to use 'float' and 'double'.
  93. format = number_to_string ((int) ieee754); // And we're printing to terminal our (rounded) number.
  94. (* printing) (format, string_length (format), file, string);
  95. } break;
  96. case 's': {
  97. char * format; // Really simple stuff, but needs some time getting used to it.
  98. format = va_arg (list, char *); // In my opinion, this should be the part of the C language itself, but oh well...
  99. (* printing) (format, string_length (format), file, string); // This could be written even shorter, but it'd require more mental-overhead.
  100. } break;
  101. default: {
  102. (* printing) ("?", 1, file, string); // Lets not abort the program in this case...
  103. } break;
  104. }
  105. // This entire switch statement can be written more shortly (in terms of lines of code) like this:
  106. // switch (format_id) {
  107. // case '%': { ... } break;
  108. // case 'i': { ... } break;
  109. // case 'f': { ... } break;
  110. // case 's': { ... } break;
  111. // default: { ... } break;
  112. // }
  113. // Choose your own preference with switch statement (and any other one), and stay consistent with how you format it.
  114. // Some people prefer more shorter lines of code, others prefer less longer lines of code (like I do).
  115. }
  116. /*
  117. Before we take a look at the actual implementation of our simple 'print' function, here's how you'd use it.
  118. @C
  119. print ("My integer is %i.\n", 404); // Prints "My integer is 404." with new line.
  120. print ("Heyo %s %s", "world", "#6!\n"); // Prints "Heyo world #6!" with new line.
  121. print ("/1Cyaa world!/-\n"); // Prints red "Cyaa world!" with new line.
  122. @
  123. Now, since we're dealing with unsafe macros, no type-checking, and in general code that I don't like to write, we have that one general printing function, which splits into 3
  124. functions, for standard output, file descriptor and string. Our general function is 'print_select', and it'll handle colouring and formating special characters for us, calling
  125. other functions we defined previously, 'print_colour' and 'print_format'. Since those 2 functions are used only once, we could just place (inline) them where they're called, but
  126. that way we'd end up with very indented code, which I'm not a fan of. I don't follow any indentation rules, I just don't indent a lot.
  127. */
  128. static void print_select (char * format, va_list list, int file, char * string) {
  129. int offset, length;
  130. length = string_length (format);
  131. for (offset = 0; offset != length; ++offset) { // We start iterating through our 'format' string, and looking for special characters below.
  132. if (format [offset] == '/') { // Colouring special character is '/', and colours are specified from '0'...'7', and '-' to cancel them.
  133. ++offset;
  134. print_colour (format [offset], file, string); // We're calling function that will colour our printed text, this one is simple.
  135. } else if (format [offset] == '%') { // And formatting special character is '%', it'll use variadic arguments!
  136. ++offset;
  137. print_format (format [offset], list, file, string); // We're calling function that will format our agruments, so we pass variable 'list'.
  138. } else {
  139. (* printing) (& format [offset], 1, file, string); // Not a special character? Okay, we'll just print them one by one.
  140. }
  141. }
  142. }
  143. /*
  144. Now, lets break down what those last 3 very similar functions do. Everything I say about 'print', is same for the other two, but with exception to their output.
  145. @C
  146. void print (char * format, ...) {
  147. va_list list; // Every variadic function needs to have this list, and sometimes you need to pass it to other functions.
  148. printing = to_output; // We're selecting different output method, notice the difference between 3 functions below, it's minimal, and this is part of it.
  149. va_start (list, format); // Every variadic function needs to start with this macro (or function depending on the implementation in <stdarg.h>).
  150. print_select (format, list, 0, NULL); // And we just call our general super smart function to handle everything for us.
  151. va_end (list); // Every variadic function needs to end with this macro... Pun intended.
  152. }
  153. @
  154. Also, needless to say, I don't usually align nor write my programs like this, I did it so you can compare those 3 functions easier. You can see what's changed, what's ignored or
  155. what's same. If you're writing something serious, align it properly, not like this please.
  156. */
  157. void print ( char * format, ...) { va_list list; printing = to_output; va_start (list, format); print_select (format, list, 0, NULL); va_end (list); }
  158. void file_print (int file, char * format, ...) { va_list list; printing = to_file; va_start (list, format); print_select (format, list, file, NULL); va_end (list); }
  159. void string_print (char * string, char * format, ...) { va_list list; printing = to_string; va_start (list, format); print_select (format, list, 0, string); va_end (list); }
  160. #endif