This repository has been archived by the owner on Jul 24, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
c.html
170 lines (157 loc) · 12 KB
/
c.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
<!doctype html><html lang="en"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1"><meta http-equiv="X-UA-Compatible" content="ie=edge"><meta name="description" content="C is a programming language that is very low-level, compiling down to assembly language."><!-- Bing --><meta name="msvalidate.01" content="45CBBE1BD8265A2217DFDA630EB8F84A" /><title>Tiny Brain Fans - C</title><link rel="stylesheet" href="tinystyle.css"></head><body>
<main id="main"><article id="content"><h1 id="title">C</h1><p>C is a programming language that is very low-level, compiling down to <a href="assembly.html">assembly</a> language.</p>
<h2>Hello, World</h2>
<h3>Code</h3>
<p>Create a new file called <code>helloworld.c</code> and add this to the contents:</p>
<pre><code class="language-c">#include <stdio.h> /* Imports the standard library for IO */
main() /* defines the function main containing no parameters */
{
printf("hello, world\n"); /* prints "hello, world" in stdio */
/* note that the newline must be placed deliberately. C does */
/* not add a newline with print like Python does. */
}
</code></pre>
<h3>Compile</h3>
<p>Then you want to compile it. The basic compiler found on UNIX computers is <code>cc</code>. Compile it by typing <code>cc helloworld.c</code>. This will create a file called <code>a.out</code>, which is the compiled version of your <code>helloworld.c</code>. </p>
<h3>Run It</h3>
<p>Run this by typing <code>./a.out</code> in your shell. You should see <code>hello, world</code> in your terminal.</p>
<h2>Basics</h2>
<h3>Comments</h3>
<pre><code class="language-c">// Single line comment
/* Multiline
comment */
</code></pre>
<h3>Constants</h3>
<h4>Symbolic Constants / <code>#define</code></h4>
<p>Symbolic constants allow the developer to avoid <a href="magic-numbers-programming.html">magic numbers</a> and add semantically useful labels to values. This is done using he syntax <code>#define NAME value</code>.</p>
<pre><code class="language-c">#include <stdio.h>
#define TAXRATE 0.09
#define SERVICECHARGE 2
main()
{
printf("The tax rate is %1.2f and the service charge is %d", TAXRATE, SERVICECHARGE);
}
/* prints "The tax rate is 0.09 and the service charge is 2"
</code></pre>
<p>These statements don't actually <em>do</em> anything in the code. They are handled by the preprocessor and the references to the <code>NAME</code> are simply replaced by the corrseponding <code>value</code> when found. So the above <code>printf</code> line, when eventually seen by the compiler, will be:</p>
<pre><code class="language-c">printf("The tax rate is %1.2f and the service charge is %d", 0.09, 2);
</code></pre>
<p>These <code>#define</code> statements are also often used for macros[11,12], so functions or subfunctions can be added in place. For example:</p>
<pre><code class="language-c">#include <stdio.h>
#define mu_assert(message, test) do { if (!(test)) return message; } while (0)
#define mu_run_test(test) do { char *message = test(); tests_run++; if (message) return message; } while (0)
int tests_run = 0;
int foo = 7;
static char * test_foo() {
mu_assert("error, foo != 7", foo == 7);
return 0;
}
static char * all_tests() {
mu_run_test(test_foo);
return 0;
}
</code></pre>
<p>Becomes effectively this after the macros are inserted:</p>
<pre><code class="language-c">#include <stdio.h>
int tests_run = 0;
int foo = 7;
static char * test_foo() {
// mu_assert("error, foo != 7", foo == 7);
do {
if (!(foo == 7)) {
return "error, foo != 7";
}
} while (0);
return 0;
}
static char * all_tests() {
//# mu_assert("error, bar != 5", bar == 5);
do {
char *message = test_foo();
tests_run++;
if (message) {
return message;
}
} while (0);
return 0;
}
</code></pre>
<p>If you want to know about the seemingly pointless loops, check it out here[11].</p>
<h4>Enumeration Constants</h4>
<p>An enumeration constant is a list of constant integer values. They will start at 0, incrementing on each new constant, unless otherwise defined.</p>
<pre><code class="language-c">enum boolean { FALSE, TRUE }; // FALSE == 0, TRUE == 1
enum months { JAN = 1, FEB, MAR, ...}; // JAN == 1, FEB == 2...
enum fib { FIRST = 1, SECOND = 1, THIRD, // THIRD == 2
FOURTH, FIFTH = 5, SIXTH = 8 } // FOURTH == 3
</code></pre>
<p>These constants can be used the same as symbolic constants.</p>
<h3>Variables</h3>
<p>Variables must be declared before they are used, usually at the beginning before executing your program. They are declared by type and then by name.</p>
<pre><code class="language-c">int num, step;
char letter;
</code></pre>
<p>Variables that exist in and only within a given function are called <strong>automatic</strong> variables. They come into existence only when the function begins and disappear when the function is finished.</p>
<p>The <code>const</code> keyword may be added to any variable declaration. This means that the variable declared will not change throughout its usage.</p>
<h4>External Variables</h4>
<p>External variables are defined exactly once outside of any function. This is so that the computer can set aside storage. Within each function that will use that, you will need to declare that variable, and preface that declaration with <code>extern</code>. For instance if <code>max</code> is an external variable, you would declare it within the function as <code>extern int max</code>.</p>
<p>If multiple source files are used, for instance defining X in one file and wanting to use it in another file, the <code>extern</code> declaration is required. If it is all in one file, they can be omitted. </p>
<p>Common practice is to define all external variables in a header file with a <code>.h</code> extension and then <code>#include</code> it in your source files.</p>
<h3>Pointers</h3>
<p>Pointers are how the CPU knows where to find a given piece of memory. Pointers are represented as integers and can be passed to functions as arguments. Since they are just numbers, you can use them also to point at elements in an array or string.</p>
<p>To declare a pointer, you preface the variable with an <strong>asterisk</strong>. You can get the address to a variable by prefacing an existing variable with an <strong>ampersand</strong>.</p>
<pre><code class="language-c">int n; // a number
int *p; // a pointer
p = &n; // point p to the address of n
</code></pre>
<p>To best understand pointers, start from the middle and go outwards, and when writing out pointers, arrays, and functions, use <code>[]</code> or <code>()</code> over <code>*</code> whenever possible. For instance[15]:</p>
<pre><code class="language-c">int *a[10];
int *a[10]; "a is"
^
int *a[10]; "a is an array"
^^^^
int *a[10]; "a is an array of pointers"
^
int *a[10]; "a is an array of pointers to `int`".
^^^
</code></pre>
<h2>Libraries</h2>
<h3>stdio.h</h3>
<h4>printf(string, [format, ...])</h4>
<p>If you use a format tag in the string, like <code>%d</code> or <code>%c</code>[14], you will need to add what will replace it in the list of <code>format</code> variables.</p>
<pre><code class="language-c">int fahr, celsius;
fahr = 100;
celsius = 37;
printf("%d F = %d C", fahr, celsius);
/* prints "100 F = 37 C" */
</code></pre>
<p>The format tags can also be accompanied by the minimum width of characters printed.</p>
<pre><code class="language-c">printf("%3d F = %3d C", fahr, celsius); /* prints "100 F = 37 C" */
printf("%2d F = %2d C", fahr, celsius); /* prints "100 F = 37 C" */
</code></pre>
<p>You can also use <code>%.*s</code> to consume two arguments: the number of chars, and the string pointer to target[12].</p>
<h4>getchar(), putchar(x)</h4>
<p><code>getchar</code> will resolve to a character from stdin, and <code>putchar(x)</code> will put the value of <code>x</code> in stdout.</p>
<h2>Sandboxing</h2>
<p>You can send text via stdin using <code>printf "123xyz" | ./program.out</code>, with program.out being the name of the compiled program.</p>
<p>You can also use an online REPL, like <a href="https://replit.com/languages/c" target="_blank">replit.com</a>.</p>
<h2>Testing</h2>
<p>There are many different options to do <a href="test-driven-development.html">test-driven development</a> in C. One I have seen recommended is MinUnit[6], as it is essentially as small as possible. Others I have seen are Minctest[8,9,10], </p>
<h2>References</h2>
<ol>
<li><a href="https://hikage.freeshell.org/books/theCprogrammingLanguage.pdf" target="_blank">https://hikage.freeshell.org/books/theCprogrammingLanguage.pdf</a></li>
<li><a href="https://stackoverflow.com/questions/19379353/symbolic-constants-in-c-define-statement" target="_blank">https://stackoverflow.com/questions/19379353/symbolic-constants-in-c-define-statement</a></li>
<li><a href="https://github.com/agavrel/42_CheatSheet" target="_blank">https://github.com/agavrel/42_CheatSheet</a></li>
<li><a href="https://www.cs.yale.edu/homes/aspnes/pinewiki/C(2f)Pointers.html" target="_blank">https://www.cs.yale.edu/homes/aspnes/pinewiki/C(2f)Pointers.html</a></li>
<li><a href="https://stackoverflow.com/questions/65820/unit-testing-c-code" target="_blank">https://stackoverflow.com/questions/65820/unit-testing-c-code</a></li>
<li><a href="https://jera.com/techinfo/jtns/jtn002" target="_blank">https://jera.com/techinfo/jtns/jtn002</a></li>
<li><a href="https://eradman.com/posts/tdd-in-c.html" target="_blank">https://eradman.com/posts/tdd-in-c.html</a></li>
<li><a href="https://github.com/codeplea/minctest" target="_blank">https://github.com/codeplea/minctest</a></li>
<li><a href="https://codeplea.com/minctest" target="_blank">https://codeplea.com/minctest</a></li>
<li><a href="https://github.com/codeplea/tinyexpr/blob/master/smoke.c" target="_blank">https://github.com/codeplea/tinyexpr/blob/master/smoke.c</a></li>
<li><a href="https://stackoverflow.com/questions/154136/why-use-apparently-meaningless-do-while-and-if-else-statements-in-macros" target="_blank">https://stackoverflow.com/questions/154136/why-use-apparently-meaningless-do-while-and-if-else-statements-in-macros</a></li>
<li><a href="https://stackoverflow.com/questions/7899119/what-does-s-mean-in-printf" target="_blank">https://stackoverflow.com/questions/7899119/what-does-s-mean-in-printf</a></li>
<li><a href="http://cslibrary.stanford.edu/101/EssentialC.pdf" target="_blank">http://cslibrary.stanford.edu/101/EssentialC.pdf</a></li>
<li><a href="https://www.ibm.com/docs/en/i/7.4?topic=functions-printf-print-formatted-characterse" target="_blank">https://www.ibm.com/docs/en/i/7.4?topic=functions-printf-print-formatted-characterse</a></li>
<li><a href="https://www.codementor.io/@dankhan/how-to-easily-decipher-complex-pointer-declarations-cpp-so24b66me" target="_blank">https://www.codementor.io/@dankhan/how-to-easily-decipher-complex-pointer-declarations-cpp-so24b66me</a></li>
</ol>
<section id="backlinks"><details><summary>Backlinks</summary><ul><li><a href="arrays-c.html">Arrays (C)</a></li><li><a href="c-data-types.html">C Data Types</a></li><li><a href="command-line-arguments-in-c.html">Command Line Arguments in C</a></li><li><a href="curses.html">Curses</a></li><li><a href="functions-c.html">Functions (C)</a></li><li><a href="regular-expressions-c.html">Regular Expressions (C)</a></li><li><a href="strings-c.html">Strings (C)</a></li><li><a href="typing.html">Typing</a></li></ul></details></section><p class="last-modified">Last modified: 202206101419</p></article></main><footer><nav><a href="index.html">Sitemap</a></nav><div class="social"><p>Built using <a href="http://codeberg.org/milofultz/swiki" target="_blank" rel="noopener noreferrer">{{SWIKI}}</a></p><p><a href="http://codeberg.org/milofultz/" target="_blank" rel="noopener noreferrer">Codeberg</a></p><p><a href="http://milofultz.com/" target="_blank" rel="noopener noreferrer">milofultz.com</a></p><p><a href="https://merveilles.town/@milofultz" target="_blank" rel="me noopener noreferrer">Mastodon</a></p></div></footer></body></html>