# C Programming/Program flow control

Very few programs follow exactly one control path and have each
instruction stated explicitly. In order to program effectively, it is
necessary to understand how one can alter the steps taken by a program
due to user input or other conditions, how some steps can be executed
many times with few lines of code, and how programs can appear to
demonstrate a rudimentary grasp of logic. C constructs known as
conditionals and loops grant this power.

From this point forward, it is necessary to understand what is usually
meant by the word *block*. A block is a group of code statements that
are associated and intended to be executed as a unit. In C, the
beginning of a block of code is denoted with { (left curly), and the end
of a block is denoted with }. It is not necessary to place a semicolon
after the end of a block. Blocks can be empty, as in {}. Blocks can also
be nested; i.e. there can be blocks of code within larger blocks.

## Conditionals

There is likely no meaningful program written in which a computer does
not demonstrate basic decision-making skills. It can actually be argued
that there is no meaningful human activity in which some sort of
decision-making, instinctual or otherwise, does not take place. For
example, when driving a car and approaching a traffic light, one does
not think, \"I will continue driving through the intersection.\" Rather,
one thinks, \"I will stop if the light is red, go if the light is green,
and if yellow go only if I am traveling at a certain speed a certain
distance from the intersection.\" These kinds of processes can be
simulated in C using conditionals.

A conditional is a statement that instructs the computer to execute a
certain block of code or alter certain data only if a specific condition
has been met. The most common conditional is the If-Else statement, with
conditional expressions and Switch-Case statements typically used as
more shorthanded methods.

Before one can understand conditional statements, it is first necessary
to understand how C expresses logical relations. C treats logic as being
arithmetic. The value 0 (zero) represents false, and ***all other
values*** represent true. If you chose some particular value to
represent true and then compare values against it, sooner or later your
code will fail when your assumed value (often 1) turns out to be
incorrect. Code written by people uncomfortable with the C language can
often be identified by the usage of #define to make a \"TRUE\" value.
[^1]

Because logic is arithmetic in C, arithmetic operators and logical
operators are one and the same. Nevertheless, there are a number of
operators that are typically associated with logic:

### Relational and Equivalence Expressions:

a \< b: 1 if **a** is less than **b**, 0 otherwise.\
a \> b: 1 if **a** is greater than **b**, 0 otherwise.\
a \<= b: 1 if **a** is less than or equal to **b**, 0 otherwise.\
a \>= b: 1 if **a** is greater than or equal to **b**, 0 otherwise.\
a == b: 1 if **a** is equal to **b**, 0 otherwise.\
a != b: 1 if **a** is not equal to **b**, 0 otherwise

New programmers should take special note of the fact that the \"equal
to\" operator is ==, not =. This is the cause of numerous coding
mistakes and is often a difficult-to-find bug, as the expression
`(a = b)` sets `a` equal to `b` and subsequently evaluates to `b`; but
the expression `(a == b)`, which is usually intended, checks if `a` is
equal to `b`. It needs to be pointed out that, if you confuse = with ==,
your mistake will often not be brought to your attention by the
compiler. A statement such as `if (c = 20) {}` is considered perfectly
valid by the language, but will always assign 20 to `c` and evaluate as
true. A simple technique to avoid this kind of bug (in many, not all
cases) is to put the constant first. This will cause the compiler to
issue an error, if == got misspelled with =.

Note that C does not have a dedicated boolean type as many other
languages do. 0 means false and anything else true. So the following are
equivalent:

``` c
 if (foo()) {
   // do something
 }
```

and

``` c
 if (foo() != 0) {
   // do something
 }
```

Often `#define TRUE 1` and `#define FALSE 0` are used to work around the
lack of a boolean type. This is bad practice, since it makes assumptions
that do not hold. It is a better idea to indicate what you are actually
expecting as a result from a function call, as there are many different
ways of indicating error conditions, depending on the situation.

``` c
 if (strstr("foo", bar) >= 0) {
   // bar contains "foo"
 }
```

Here, `strstr` returns the index where the substring foo is found and -1
if it was not found. Note that this would fail with the `TRUE`
definition mentioned in the previous paragraph. It would also not
produce the expected results if we omitted the `>= 0`.

One other thing to note is that the relational expressions do not
evaluate as they would in mathematical texts. That is, an expression
`myMin < value < myMax` does not evaluate as you probably think it
might. Mathematically, this would test whether or not *value* is between
*myMin* and *myMax*. But in C, what happens is that *value* is first
compared with *myMin*. This produces either a 0 or a 1. It is this value
that is compared against myMax. Example:

``` c
 int value = 20;
 /* ... */
 if (0 < value < 10) { // don't do this! it always evaluates to "true"!
   /* do some stuff */
 }
```

Because *value* is greater than 0, the first comparison produces a value
of 1. Now 1 is compared to be less than 10, which is true, so the
statements in the if are executed. This probably is not what the
programmer expected. The appropriate code would be:

``` c
 int value = 20;
 /* ... */
 if (0 < value && value < 10) {   // the && means "and"
   /* do some stuff */
 }
```

### Logical Expressions

a \|\| b: when EITHER **a** or **b** is true (or both), the result is 1, otherwise the result is 0.\
a && b: when BOTH **a** and **b** are true, the result is 1, otherwise the result is 0.\
!a: when **a** is true, the result is 0; when **a** is 0, the result is 1.

Here\'s an example of a larger logical expression. In the statement:

`  e = ((a && b) || (c > d));`

e is set equal to 1 if a and b are non-zero, or if c is greater than d.
In all other cases, e is set to 0.

C uses short circuit evaluation of logical expressions. That is to say,
once it is able to determine the truth of a logical expression, it does
no further evaluation. This is often useful as in the following:

`int myArray[12];`\
`....`\
`if (i < 12 && myArray[i] > 3) { `\
`....`

In the snippet of code, the comparison of i with 12 is done first. If it
evaluates to 0 (false), **i** would be out of bounds as an index to
**myArray**. In this case, the program never attempts to access
**myArray\[i\]** since the truth of the expression is known to be false.
Hence we need not worry here about trying to access an out-of-bounds
array element if it is already known that i is greater than or equal to
zero. A similar thing happens with expressions involving the or \|\|
operator.

`while (doThis() || doThat()) ...`

doThat() is never called if doThis() returns a non-zero (true) value.

### The If-Else statement

If-Else provides a way to instruct the computer to execute a block of
code only if certain conditions have been met. The syntax of an If-Else
construct is:

``` c
 if (/* condition goes here */) {
   /* if the condition is non-zero (true), this code will execute */
 } else {
   /* if the condition is 0 (false), this code will execute */
 }
```

The first block of code executes if the condition in parentheses
directly after the *if* evaluates to non-zero (true); otherwise, the
second block executes.

The *else* and following block of code are completely optional. If there
is no need to execute code if a condition is not true, leave it out.

Also, keep in mind that an *if* can directly follow an *else* statement.
While this can occasionally be useful, chaining more than two or three
if-elses in this fashion is considered bad programming practice. We can
get around this with the Switch-Case construct described later.

Two other general syntax notes need to be made that you will also see in
other control constructs: First, note that there is no semicolon after
*if* or *else*. There could be, but the block (code enclosed in { and })
takes the place of that. Second, if you only intend to execute one
statement as a result of an *if* or *else*, curly braces are not needed.
However, many programmers believe that inserting curly braces anyway in
this case is good coding practice.

The following code sets a variable c equal to the greater of two
variables a and b, or 0 if a and b are equal.

``` c
 if (a > b) {
   c = a;
 } else if (b > a) {
   c = b;
 } else {
   c = 0;
 }
```

Consider this question: why can\'t you just forget about *else* and
write the code like:

``` c
 if (a > b) {
   c = a;
 }

 if (a < b) {
   c = b;
 }

 if (a == b) {
   c = 0;
 }
```

There are several answers to this. Most importantly, if your
conditionals are not mutually exclusive, *two* cases could execute
instead of only one. If the code was different and the value of a or b
changes somehow (e.g.: you reset the lesser of a and b to 0 after the
comparison) during one of the blocks? You could end up with multiple
*if* statements being invoked, which is not your intent. Also,
evaluating *if* conditionals takes processor time. If you use *else* to
handle these situations, in the case above assuming (a \> b) is non-zero
(true), the program is spared the expense of evaluating additional *if*
statements. The bottom line is that it is usually best to insert an
*else* clause for all cases in which a conditional will not evaluate to
non-zero (true).

#### The conditional expression

A conditional expression is a way to set values conditionally in a more
shorthand fashion than If-Else. The syntax is:

`(/* logical expression goes here */) ? (/* if non-zero (true) */) : (/* if 0 (false) */)`

The logical expression is evaluated. If it is non-zero (true), the
overall conditional expression evaluates to the expression placed
between the ? and :, otherwise, it evaluates to the expression after the
:. Therefore, the above example (changing its function slightly such
that c is set to b when a and b are equal) becomes:

`c = (a > b) ? a : b;`

Conditional expressions can sometimes clarify the intent of the code.
Nesting the conditional operator should usually be avoided. It\'s best
to use conditional expressions only when the expressions for a and b are
simple. Also, contrary to a common beginner belief, conditional
expressions do not make for faster code. As tempting as it is to assume
that fewer lines of code result in faster execution times, there is no
such correlation.

### The Switch-Case statement

Say you write a program where the user inputs a number 1-5
(corresponding to student grades, A(represented as 1)-D(4) and F(5)),
stores it in a variable **grade** and the program responds by printing
to the screen the associated letter grade. If you implemented this using
If-Else, your code would look something like this:

``` c
 if (grade == 1) {
   printf("A\n");
 } else if (grade == 2) {
   printf("B\n");
 } else if /* etc. etc. */
```

Having a long chain of if-else-if-else-if-else can be a pain, both for
the programmer and anyone reading the code. Fortunately, there\'s a
solution: the Switch-Case construct, of which the basic syntax is:

``` c
 switch (/* integer or enum goes here */) {
 case /* potential value of the aforementioned int or enum */:
   /* code */
 case /* a different potential value */:
   /* different code */
 /* insert additional cases as needed */
 default:
   /* more code */
 }
```

The Switch-Case construct takes a variable, usually an int or an enum,
placed after *switch*, and compares it to the value following the *case*
keyword. If the variable is equal to the value specified after *case*,
the construct \"activates\", or begins executing the code after the case
statement. Once the construct has \"activated\", there will be no
further evaluation of *case*s.

Switch-Case is syntactically \"weird\" in that no braces are required
for code associated with a *case*.

***Very important***: Typically, the last statement for each case is a
break statement. This causes program execution to jump to the statement
following the closing bracket of the switch statement, which is what one
would normally want to happen. However if the break statement is
omitted, program execution continues with the first line of the next
case, if any. This is called a *fall-through*. When a programmer desires
this action, a comment should be placed at the end of the block of
statements indicating the desire to fall through. Otherwise another
programmer maintaining the code could consider the omission of the
\'break\' to be an error, and inadvertently \'correct\' the problem.
Here\'s an example:

``` c
 switch (someVariable) {
 case 1:
   printf("This code handles case 1\n");
   break;
 case 2:
   printf("This prints when someVariable is 2, along with...\n");
   /* FALL THROUGH */
 case 3:
   printf("This prints when someVariable is either 2 or 3.\n" );
   break;
 }
```

If a *default* case is specified, the associated statements are executed
if none of the other cases match. A *default* case is optional. Here\'s
a switch statement that corresponds to the sequence of if - else if
statements above.

Back to our example above. Here\'s what it would look like as
Switch-Case:

``` c
 switch (grade) {
 case 1:
   printf("A\n");
   break;
 case 2:
   printf("B\n");
   break;
 case 3:
   printf("C\n");
   break;
 case 4:
   printf("D\n");
   break;
 default:
   printf("F\n");
   break;
 }
```

A set of statements to execute can be grouped with more than one value
of the variable as in the following example. (the fall-through comment
is not necessary here because the intended behavior is obvious)

``` c
 switch (something) {
 case 2:
 case 3:
 case 4:
   /* some statements to execute for 2, 3 or 4 */
   break;
 case 1:
 default:
   /* some statements to execute for 1 or other than 2,3,and 4 */
   break;
 }
```

Switch-Case constructs are particularly useful when used in conjunction
with user defined *enum* data types. Some compilers are capable of
warning about an unhandled enum value, which may be helpful for avoiding
bugs.

## Loops

Often in computer programming, it is necessary to perform a certain
action a certain number of times or until a certain condition is met. It
is impractical and tedious to simply type a certain statement or group
of statements a large number of times, not to mention that this approach
is too inflexible and unintuitive to be counted on to stop when a
certain event has happened. As a real-world analogy, someone asks a
dishwasher at a restaurant what he did all night. He will respond, \"I
washed dishes all night long.\" He is not likely to respond, \"I washed
a dish, then washed a dish, then washed a dish, then\...\". The
constructs that enable computers to perform certain repetitive tasks are
called loops.

### While loops

A while loop is the most basic type of loop. It will run as long as the
condition is non-zero (true). For example, if you try the following, the
program will appear to lock up and you will have to manually close the
program down. A situation where the conditions for exiting the loop will
never become true is called an infinite loop.

``` c
 int a = 1;
 while (42) {
   a = a * 2;
 }
```

Here is another example of a while loop. It prints out all the powers of
two less than 100.

``` c
 int a = 1;
 while (a < 100) {
   printf("a is %d \n", a);
   a = a * 2;
 }
```

The flow of all loops can also be controlled by **break** and
**continue** statements. A break statement will immediately exit the
enclosing loop. A continue statement will skip the remainder of the
block and start at the controlling conditional statement again. For
example:

``` c
 int a = 1;
 while (42) { // loops until the break statement in the loop is executed
   printf("a is %d ", a);
   a = a * 2;
   if (a > 100) {
     break;
   } else if (a == 64) {
     continue;  // Immediately restarts at while, skips next step
   }
   printf("a is not 64\n");
 }
```

In this example, the computer prints the value of a as usual, and prints
a notice that a is not 64 (unless it was skipped by the continue
statement).

Similar to If above, braces for the block of code associated with a
While loop can be omitted if the code consists of only one statement,
for example:

``` c
 int a = 1;
 while (a < 100)
   a = a * 2;
```

This will merely increase a until a is not less than 100.

When the computer reaches the end of the while loop, it always goes back
to the while statement at the top of the loop, where it re-evaluates the
controlling condition. If that condition is \"true\" at that instant \--
even if it was temporarily 0 for a few statements inside the loop \--
then the computer begins executing the statements inside the loop again;
otherwise the computer exits the loop. The computer does not
\"continuously check\" the controlling condition of a while loop during
the execution of that loop. It only \"peeks\" at the controlling
condition each time it reaches the `while` at the top of the loop.

It is very important to note, once the controlling condition of a While
loop becomes 0 (false), the loop will not terminate until the block of
code is finished and it is time to reevaluate the conditional. If you
need to terminate a While loop immediately upon reaching a certain
condition, consider using **break**.

A common idiom is to write:

``` c
 int i = 5;
 while (i--) {
   printf("java and c# can't do this\n");
 }
```

This executes the code in the while loop 5 times, with i having values
that range from 4 down to 0 (inside the loop). Conveniently, these are
the values needed to access every item of an array containing 5
elements.

### For loops

For loops generally look something like this:

`for (`*`initialization`*`; `*`test`*`; `*`increment`*`) {`\
`  /* code */`\
`}`

The *initialization* statement is executed exactly once - before the
first evaluation of the *test* condition. Typically, it is used to
assign an initial value to some variable, although this is not strictly
necessary. The *initialization* statement can also be used to declare
and initialize variables used in the loop.

The *test* expression is evaluated each time before the code in the
*for* loop executes. If this expression evaluates as 0 (false) when it
is checked (i.e. if the expression is not true), the loop is not
(re)entered and execution continues normally at the code immediately
following the FOR-loop. If the expression is non-zero (true), the code
within the braces of the loop is executed.

After each iteration of the loop, the *increment* statement is executed.
This often is used to increment the loop index for the loop, the
variable initialized in the initialization expression and tested in the
test expression. Following this statement execution, control returns to
the top of the loop, where the *test* action occurs. If a *continue*
statement is executed within the *for* loop, the increment statement
would be the next one executed.

Each of these parts of the for statement is optional and may be omitted.
Because of the free-form nature of the for statement, some fairly fancy
things can be done with it. Often a for loop is used to loop through
items in an array, processing each item at a time.

``` c
 int myArray[12];
 int ix;
 for (ix = 0; ix < 12; ix++) {
   myArray[ix] = 5 * ix + 3;
 }
```

The above for loop initializes each of the 12 elements of myArray. The
loop index can start from any value. In the following case it starts
from 1.

``` c
 for (ix = 1; ix <= 10; ix++) {
   printf("%d ", ix);
 }
```

which will print

**`1 2 3 4 5 6 7 8 9 10`**

You will most often use loop indexes that start from 0, since arrays are
indexed at zero, but you will sometimes use other values to initialize a
loop index as well.

The *increment* action can do other things, such as *decrement*. So this
kind of loop is common:

``` c
 for (i = 5; i > 0; i--) {
   printf("%d ", i);
 }
```

which yields

**`5 4 3 2 1`**

Here\'s an example where the test condition is simply a variable. If the
variable has a value of 0 or NULL, the loop exits, otherwise the
statements in the body of the loop are executed.

``` c
 for (t = list_head; t; t = NextItem(t)) {
   /* body of loop */
 }
```

A WHILE loop can be used to do the same thing as a FOR loop, however a
FOR loop is a more condensed way to perform a set number of repetitions
since all of the necessary information is in a one line statement.

A FOR loop can also be given no conditions, for example:

``` c
 for (;;) {
   /* block of statements */
 }
```

This is called an infinite loop since it will loop forever unless there
is a break statement within the statements of the for loop. The empty
test condition effectively evaluates as true.

It is also common to use the comma operator in for loops to execute
multiple statements.

``` c
 int i, j, n = 10;
 for (i = 0, j = 0; i <= n; i++, j += 2) {
   printf("i = %d , j = %d \n", i, j);
 }
```

Special care should be taken when designing or refactoring the
conditional part, especially whether using \< or \<= , whether start and
stop should be corrected by 1, and in case of prefix- and
postfix-notations. ( On a 100 yards promenade with a tree every 10 yards
there are 11 trees. )

``` c
 int i, n = 10;
 for (i = 0; i < n; i++)
   printf("%d ", i); // processed n times => 0 1 2 3 ... (n-1)
 printf("\n");
 for (i = 0; i <= n; i++)
   printf("%d ", i); // processed (n+1) times => 0 1 2 3 ... n
 printf("\n");
 for (i = n; i--;)
   printf("%d ", i); // processed n times => (n-1) ...3 2 1 0
 printf("\n");
 for (i = n; --i;)
   printf("%d ", i); // processed (n-1) times => (n-1) ...4 3 2 1
 printf("\n");
```

### Do-While loops

A DO-WHILE loop is a post-check while loop, which means that it checks
the condition after each run. As a result, even if the condition is zero
(false), it will run at least once. It follows the form of:

``` c
 do {
   /* do stuff */
 } while (condition);
```

Note the terminating semicolon. This is required for correct syntax.
Since this is also a type of while loop, **break** and **continue**
statements within the loop function accordingly. A **continue**
statement causes a jump to the test of the condition and a *break*
statement exits the loop.

It is worth noting that Do-While and While are functionally almost
identical, with one important difference: Do-While loops are always
guaranteed to execute at least once, but While loops will not execute at
all if their condition is 0 (false) on the first evaluation.

## One last thing: goto

**goto** is a very simple and traditional control mechanism. It is a
statement used to immediately and unconditionally jump to another line
of code. To use goto, you must place a label at a point in your program.
A label consists of a name followed by a colon (:) on a line by itself.
Then, you can type \"goto *label*;\" at the desired point in your
program. The code will then continue executing beginning with *label*.
This looks like:

``` c
 MyLabel:
   /* some code */
   goto MyLabel;
```

The ability to transfer the flow of control enabled by gotos is so
powerful that, in addition to the simple if, all other control
constructs can be written using gotos instead. Here, we can let \"S\"
and \"T\" be any arbitrary statements:

``` c
 if (''cond'') {
   S;
 } else {
   T;
 }
 /* ... */
```

The same statement could be accomplished using two gotos and two labels:

``` c
 if (''cond'') goto Label1;
   T;
   goto Label2;
 Label1:
   S;
 Label2:
   /* ... */
```

Here, the first goto is conditional on the value of \"cond\". The second
goto is unconditional. We can perform the same translation on a loop:

``` c
 while (''cond1'') {
   S;
   if (''cond2'')
     break;
   T;
 }
 /* ... */
```

Which can be written as:

``` c
 Start:
   if (!''cond1'') goto End;
   S;
   if (''cond2'') goto End;
   T;
   goto Start;
 End:
   /* ... */
```

As these cases demonstrate, often the structure of what your program is
doing can usually be expressed without using gotos. Undisciplined use of
gotos can create unreadable, unmaintainable code when more idiomatic
alternatives (such as if-elses, or for loops) can better express your
structure. Theoretically, the goto construct does not ever *have* to be
used, but there are cases when it can increase readability, avoid code
duplication, or make control variables unnecessary. You should consider
first mastering the idiomatic solutions, and use goto only when
necessary. Keep in mind that many, if not most, C style guidelines
*strictly forbid* use of **goto**, with the only common exceptions being
the following examples.

One use of goto is to break out of a deeply nested loop. Since **break**
will not work (it can only escape one loop), **goto** can be used to
jump completely outside the loop. Breaking outside of deeply nested
loops without the use of the goto is always possible, but often involves
the creation and testing of extra variables that may make the resulting
code far less readable than it would be with **goto**. The use of
**goto** makes it easy to undo actions in an orderly fashion, typically
to avoid failing to free memory that had been allocated.

Another accepted use is the creation of a state machine. This is a
fairly advanced topic though, and not commonly needed.

## Examples

``` c

#include <errno.h>
#include <stdio.h>
#include <stdlib.h>

int main(void)
{
    int years;

    printf("Enter your age in years : ");
    fflush(stdout);
    errno = 0;
    if (scanf("%d", &years) != 1 || errno)
        return EXIT_FAILURE;
    printf("Your age in days is %d\n", years * 365);
    return 0;
}
```

## References

de:C-Programmierung:
Kontrollstrukturen
et:Programmeerimiskeel
C/Keelestruktuurid
fr:Programmation C/Tests
pl:C/Instrukcje sterujące
pt:Programar em C/Controle de
fluxo
fi:C/Ohjausrakenteet

[^1]: C FAQ


# C Programming/Procedures and functions

In C programming, all executable code resides within a **function**.
Note that other programming languages may distinguish between a
\"function\", \"subroutine\", \"subprogram\", \"procedure\", or
\"method\" \-- in C, these are all functions. Functions are a
fundamental feature of any high level programming language and make it
possible to tackle large, complicated tasks by breaking tasks into
smaller, more manageable pieces of code.

At a lower level, a function is nothing more than a memory address where
the instructions associated with a function reside in your computer\'s
memory. In the source code, this memory address is usually given a
descriptive name which programmers can use to **call** the function and
execute the instructions that begin at the function\'s starting address.
The instructions associated with a function are frequently referred to
as a **block** of code. After the function\'s instructions finish
executing, the function can return a value and code execution will
resume with the instruction that immediately follows the initial call to
the function. If this doesn\'t make immediate sense to you, don\'t
worry. Understanding what is happening inside your computer at the
lowest levels can be confusing at first, but will eventually become very
intuitive as you develop your C programming skills.

For now, it\'s enough to know that a function and its associated block
of code is often executed (called) several times, from several different
places, during a single execution of a program.

As a basic example, suppose you are writing a program that calculates
the distance of a given (x,y) point to the x-axis and to the y-axis. You
will need to compute the absolute value of the whole numbers x and y. We
could write it like this (assuming we don\'t have a predefined function
for absolute value in any library):

``` c
#include <stdio.h>

/*this function computes the absolute value of a whole number.*/
int abs(int x)
{
        if (x>=0) return x;
        else return -x;
}

/*this program calls the abs() function defined above twice.*/
int main()
{
        int x, y;

        printf("Type the coordinates of a point in 2-plane, say P = (x,y). First x=");
        scanf("%d", &x);
        printf("Second y=");
        scanf("%d", &y);

        printf("The distance of the P point to the x-axis is %d. \n Its distance to the y-axis is %d. \n", abs(y), abs(x));

        return 0;
}
```

The next example illustrates the usage of a function as a procedure.
It\'s a simplistic program that asks students for their grade for three
different courses and tells them if they passed a course. Here, we
created a function, called `check()` that can be called as many times as
we need to. The function saves us from having to write the same set of
instructions for each class the student has taken.

``` c
#include<stdio.h>

/*the 'check' function is defined here.*/
void check(int x)
{
        if (x<60)
                printf("Sorry! You will need to try this course again.\n");
        else
                printf("Enjoy your vacation! You have passed.\n");
}

/*the program starts here at the main() function, which calls the check() function three times.*/
int main()
{
        int a, b, c;

        printf("Type your grade in Mathematics (whole number). \n");
        scanf("%d", &a);
        check(a);

        printf("Type your grade in Science (whole number). \n");
        scanf("%d", &b);
        check(b);

        printf("Type your grade in Programming (whole number). \n");
        scanf("%d", &c);
        check(c);

        /* this program should be replaced by something more meaningful.*/
        return 0;
}
```

Notice that in the program above, there is no outcome value for the
\'check\' function. It only executes a procedure.

This is precisely what functions are for.

## More on functions

It\'s useful to conceptualize a function like a machine in a factory. On
the input side of the machine, you dump in the \"raw materials,\" or the
input data, that you want the machine to process. Then the machine goes
to work and and spits out a finished product, the \"return value,\" to
the output side of the machine which you can collect and use for other
purposes.

In C, you must tell the machine exactly what raw materials it is
expected to process and what kind of finished product you want the
machine to return to you. If you supply the machine with different raw
materials than it expects, or if you try to return a product that\'s
different than what you told the machine to produce, the C compiler will
throw an error.

Note that a function isn\'t required to take any inputs. It doesn\'t
have to return anything back to us, either. If we modify the example
above to ask the user for their grade inside the `check` function, there
would be no need to pass the grade value into the function. And notice
that the `check` doesn\'t pass a value back. The function just prints
out a message to the screen.

You should be familiar with some basic terminology related to functions:

-   A function, call it *f*, that uses another function *g*, is said to
    *call* *g*. For example, *f* calls *g* to print the squares of ten
    numbers. *f* is referred to as the *caller* function and *g* is the
    *callee*.
-   The inputs we send to a function are called its *arguments*. When we
    declare our function, we describe the *parameters* that determine
    what type of *arguments* are acceptable to pass into the function.
    We describe these parameters to the compiler inside a set of
    parentheses next to the function\'s name.
-   A function *g* that gives some kind of answer back to *f* is said to
    *return* that answer or value. For example, *g* returns the sum of
    its arguments.

## Writing functions in C

It\'s always good to learn by example. Let\'s write a function that will
return the square of a number.

``` c
int square(int x)
{
   int square_of_x;
   square_of_x = x * x;
   return square_of_x;
}
```

To understand how to write such a function like this, it may help to
look at what this function does as a whole. It takes in an `int`, x, and
squares it, storing it in the variable square_of_x. Now this value is
returned.

The first int at the beginning of the function declaration is the type
of data that the function returns. In this case when we square an
integer we get an integer, and we are returning this integer, and so we
write `int` as the return type.

Next is the name of the function. It is good practice to use meaningful
and descriptive names for functions you may write. It may help to name
the function after what it is written to do. In this case we name the
function \"square\", because that\'s what it does - it squares a number.

Next is the function\'s first and only argument, an `int`, which will be
referred to in the function as x. This is the function\'s *input*.

In between the braces is the actual guts of the function. It declares an
integer variable called square_of_x that will be used to hold the value
of the square of x. Note that the variable square_of_x can **only** be
used within this function, and not outside. We\'ll learn more about this
sort of thing later, and we will see that this property is very useful.

We then assign x multiplied by x, or x squared, to the variable
square_of_x, which is what this function is all about. Following this is
a `return` statement. We want to return the value of the square of x, so
we must say that this function returns the contents of the variable
square_of_x.

Our brace to close, and we have finished the declaration.

Written in a more concise manner, this code performs exactly the same
function as the above:

``` c
int square(int x)
{
   return x * x;
}
```

Note this should look familiar - you have been writing functions
already, in fact - main is a function that is always written.

### In general

In general, if we want to declare a function, we write

` `*`type`*` `*`name`*`(`*`type1`*` `*`arg1`*`, `*`type2`*` `*`arg2`*`, ...)`\
` {`\
`   /* `*`code`*` */`\
` } `

We\'ve previously said that a function can take no arguments, or can
return nothing, or both. What do we write if we want the function to
return nothing? We use C\'s `void` keyword. `void` basically means
\"nothing\" - so if we want to write a function that returns nothing,
for example, we write

``` c
void sayhello(int number_of_times)
{
  int i;
  for(i=1; i <= number_of_times; i++) {
     printf("Hello!\n");
  }
}
```

Notice that there is no `return` statement in the function above. Since
there\'s none, we write `void` as the return type. (Actually, one can
use the `return` keyword in a procedure to return to the caller before
the end of the procedure, but one cannot return a value as if it were a
function.)

What about a function that takes no arguments? If we want to do this, we
can write for example

``` c
float calculate_number(void)
{
  float to_return=1;
  int i;
  for(i=0; i < 100; i++) {
     to_return += 1;
     to_return = 1/to_return;
  }
  return to_return;
}
```

Notice this function doesn\'t take any inputs, but merely returns a
number calculated by this function.

Naturally, you can combine both void return and void in arguments
together to get a valid function, also.

### Recursion

Here\'s a simple function that does an infinite loop. It prints a line
and calls itself, which again prints a line and calls itself again, and
this continues until the stack overflows and the program crashes. A
function calling itself is called recursion, and normally you will have
a conditional that would stop the recursion after a small, finite number
of steps.

``` c
      // don't run this!
void infinite_recursion()
{
    printf("Infinite loop!\n");
    infinite_recursion();
}
```

A simple check can be done like this. Note that ++depth is used so the
increment will take place before the value is passed into the function.
Alternatively you can increment on a separate line before the recursion
call. If you say print_me(3,0); the function will print the line
Recursion 3 times.

``` c
void print_me(int j, int depth)
{
   if(depth < j) {
       printf("Recursion! depth = %d j = %d\n",depth,j); //j keeps its value
       print_me(j, ++depth);
   }
}
```

Recursion is most often used for jobs such as directory tree scans,
seeking for the end of a linked list, parsing a tree structure in a
database and factorising numbers (and finding primes) among other
things.

### Static functions

If a function is to be called only from within the file in which it is
declared, it is appropriate to declare it as a static function. When a
function is declared static, the compiler will know to compile an object
file in a way that prevents the function from being called from code in
other files. Example:

``` c
static int compare( int a, int b )
{
    return (a+4 < b)? a : b;
}
```

## Using C functions

We can now *write* functions, but how do we use them? When we write
main, we place the function outside the braces that encompass main.

When we want to use that function, say, using our `calculate_number`
function above, we can write something like

``` c
 float f;
 f = calculate_number();
```

If a function takes in arguments, we can write something like

``` c
 int square_of_10;
 square_of_10 = square(10);
```

If a function doesn\'t return anything, we can just say

``` c
 say_hello();
```

since we don\'t need a variable to catch its return value.

## Functions from the C Standard Library

While the C language doesn\'t itself contain functions, it is usually
linked with the C Standard Library. To use this library, you need to add
an #include directive at the top of the C file, which may be one of the
following from C89/C90:

+---------------+---------------+---------------+---------------+---+
| -             | -             | -             | -             |   |
|   `<assert.h |   `<limits.h |   [`<signal.h |   [`<stdlib.h |   |
| >` | h "wikilink") | h "wikilink") | h "wikilink") |   |
| -   `<ctype. | -             | -             | -             |   |
| h>` | >` | h "wikilink") | h "wikilink") |   |
| h>` | .h>`](w:Math. |   `<stddef.h | .h>` | >`](w:Stddef. | h "wikilink") |   |
| h>`](w:Float. | -             | h "wikilink") |               |   |
| h "wikilink") |   `<setjmp.h | -   [`<stdio. |               |   |
|               | >` | h "wikilink") |               |   |
+---------------+---------------+---------------+---------------+---+

The functions available are:

+----------------+----------------+----------------+----------------+
| `<assert.h>`   | `<limits.h>`   | `<signal.h>`   | `<stdlib.h>`   |
+================+================+================+================+
| -              | -   (constants | -   int        | -              |
|    assert(int) |     only)      |     raise(int  |  atof(char\*), |
|                |                |     sig). This |                |
|                |                | -   void\*     |  atoi(char\*), |
|                |                |     signal(int |                |
|                |                |     sig, void  |   atol(char\*) |
|                |                |                | -              |
|                |                | (\*func)(int)) |    strtod(char |
|                |                |                |     \* str,    |
|                |                |                |     char \*\*  |
|                |                |                |     endptr ),  |
|                |                |                |                |
|                |                |                |    strtol(char |
|                |                |                |     \*str,     |
|                |                |                |     char       |
|                |                |                |                |
|                |                |                |   \*\*endptr), |
|                |                |                |                |
|                |                |                |   strtoul(char |
|                |                |                |     \*str,     |
|                |                |                |     char       |
|                |                |                |                |
|                |                |                |    \*\*endptr) |
|                |                |                | -   rand(),    |
|                |                |                |     srand()    |
|                |                |                | -   m          |
|                |                |                | alloc(size_t), |
|                |                |                |     calloc     |
|                |                |                |     (size_t    |
|                |                |                |     elements,  |
|                |                |                |     size_t     |
|                |                |                |                |
|                |                |                |  elementSize), |
|                |                |                |     r          |
|                |                |                | ealloc(void\*, |
|                |                |                |     int)       |
|                |                |                | -   free       |
|                |                |                |     (void\*)   |
|                |                |                | -   exit(int), |
|                |                |                |     abort()    |
|                |                |                | -              |
|                |                |                |    atexit(void |
|                |                |                |                |
|                |                |                |    (\*func)()) |
|                |                |                | -   getenv     |
|                |                |                | -   system     |
|                |                |                | -   qsort(void |
|                |                |                |     \*, size_t |
|                |                |                |     number,    |
|                |                |                |     size_t     |
|                |                |                |     size, int  |
|                |                |                |     (\*sor     |
|                |                |                | tfunc)(void\*, |
|                |                |                |     void\*))   |
|                |                |                | -   abs, labs  |
|                |                |                | -   div, ldiv  |
+----------------+----------------+----------------+----------------+
| `<ctype.h>`    | `<locale.h>`   | `<stdarg.h>`   | `<string.h>`   |
+----------------+----------------+----------------+----------------+
| -   isalnum,   | -   struct     | -   va_start   | -   memcpy,    |
|     isalpha,   |     lconv\*    |     (va_list,  |     memmove    |
|     isblank    |     loc        |     ap)        | -   memchr,    |
| -   iscntrl,   | aleconv(void); | -   va_arg     |     memcmp,    |
|     isdigit,   | -   char\*     |     (ap,       |     memset     |
|     isgraph    |                |     (type))    | -   strcat,    |
| -   islower,   | setlocale(int, | -   va_end     |     strncat,   |
|     isprint,   |     const      |     (ap)       |     strchr,    |
|     ispunct    |     char\*);   | -   va_copy    |     strrchr    |
| -   isspace,   |                |     (va_list,  | -   strcmp,    |
|     isupper,   |                |     va_list)   |     strncmp,   |
|     isxdigit   |                |                |     strccoll   |
| -   tolower,   |                |                | -   strcpy,    |
|     toupper    |                |                |     strncpy    |
|                |                |                | -   strerror   |
|                |                |                | -   strlen     |
|                |                |                | -   strspn,    |
|                |                |                |     strcspn    |
|                |                |                | -   strpbrk    |
|                |                |                | -   strstr     |
|                |                |                | -   strtok     |
|                |                |                | -   strxfrm    |
+----------------+----------------+----------------+----------------+
| errno.h        | math.h         | stddef.h       | time.h         |
+----------------+----------------+----------------+----------------+
| -   (errno)    | -   sin, cos,  | -   offsetof   | -   asctime    |
|                |     tan        |     macro      |     (struct    |
|                | -   asin,      |                |     tm\*       |
|                |     acos,      |                |     tmptr)     |
|                |     atan,      |                | -   clock_t    |
|                |     atan2      |                |     clock()    |
|                | -   sinh,      |                | -   char\*     |
|                |     cosh, tanh |                |                |
|                | -   ceil       |                |    ctime(const |
|                | -   exp        |                |     time_t\*   |
|                | -   fabs       |                |     timer)     |
|                | -   floor      |                | -   double     |
|                | -   fmod       |                |     d          |
|                | -   frexp      |                | ifftime(time_t |
|                | -   ldexp      |                |     timer2,    |
|                | -   log, log10 |                |     time_t     |
|                | -   modf       |                |     timer1)    |
|                | -   pow        |                | -   struct     |
|                | -   sqrt       |                |     tm\*       |
|                |                |                |                |
|                |                |                |   gmtime(const |
|                |                |                |     time_t\*   |
|                |                |                |     timer)     |
|                |                |                | -   struct     |
|                |                |                |     tm\*       |
|                |                |                |                |
|                |                |                | gmtime_r(const |
|                |                |                |     time_t\*   |
|                |                |                |     timer,     |
|                |                |                |     struct     |
|                |                |                |     tm\*       |
|                |                |                |     result)    |
|                |                |                | -   struct     |
|                |                |                |     tm\*       |
|                |                |                |     l          |
|                |                |                | ocaltime(const |
|                |                |                |     time_t\*   |
|                |                |                |     timer)     |
|                |                |                | -   time_t     |
|                |                |                |                |
|                |                |                |  mktime(struct |
|                |                |                |     tm\* ptm)  |
|                |                |                | -   time_t     |
|                |                |                |                |
|                |                |                |  time(time_t\* |
|                |                |                |     timer)     |
|                |                |                | -   char \*    |
|                |                |                |                |
|                |                |                | strptime(const |
|                |                |                |     char\*     |
|                |                |                |     buf, const |
|                |                |                |     char\*     |
|                |                |                |     format,    |
|                |                |                |     struct     |
|                |                |                |     tm\* tptr) |
|                |                |                | -   time_t     |
|                |                |                |                |
|                |                |                |  timegm(struct |
|                |                |                |     tm         |
|                |                |                |                |
|                |                |                |  \*brokentime) |
+----------------+----------------+----------------+----------------+
| float.h        | setjmp.h       | stdio.h        |                |
+----------------+----------------+----------------+----------------+
| -              | -   int        | -   fclose     | -   fread,     |
|    (constants) |                | -   fopen,     |     fwrite     |
|                | setjmp(jmp_buf |     freopen    | -   getc, putc |
|                |     env)       | -   remove     | -   getchar,   |
|                | -   void       | -   rename     |     putchar,   |
|                |     l          | -   rewind     |     fputchar   |
|                | ongjmp(jmp_buf | -   tmpfile    | -   gets, puts |
|                |     env, int   | -   clearerr   | -   printf,    |
|                |     value)     | -   feof,      |     vprintf    |
|                |                |     ferror     | -   fprintf,   |
|                |                | -   fflush     |     vfprintf   |
|                |                | -   fgetpos,   | -   sprintf,   |
|                |                |     fsetpos    |     snprintf,  |
|                |                | -   fgetc,     |     vsprintf,  |
|                |                |     fputc      |     vsnprintf  |
|                |                | -   fgets,     | -   perror     |
|                |                |     fputs      | -   scanf,     |
|                |                | -   ftell,     |     vscanf     |
|                |                |     fseek      | -   fscanf,    |
|                |                |                |     vfscanf    |
|                |                |                | -   sscanf,    |
|                |                |                |     vsscanf    |
|                |                |                | -   setbuf,    |
|                |                |                |     setvbuf    |
|                |                |                | -   tmpnam     |
|                |                |                | -   ungetc     |
+----------------+----------------+----------------+----------------+

## Variable-length argument lists

Functions with variable-length argument lists are functions that can
take a varying number of arguments. An example in the C standard library
is the `printf` function, which can take any number of arguments
depending on how the programmer wants to use it.

C programmers rarely find the need to write new functions with
variable-length arguments. If they want to pass a bunch of things to a
function, they typically define a structure to hold all those things \--
perhaps a linked list, or an array \-- and call that function with the
data in the arguments.

However, you may occasionally find the need to write a new function that
supports a variable-length argument list. To create a function that can
accept a variable-length argument list, you must first include the
standard library header `stdarg.h`. Next, declare the function as you
would normally. Next, add as the last argument an ellipsis (\"\...\").
This indicates to the compiler that a variable list of arguments is to
follow. For example, the following function declaration is for a
function that returns the average of a list of numbers:

``` c
  float average (int n_args, ...);
```

Note that because of the way variable-length arguments work, we must
somehow, in the arguments, specify the number of elements in the
variable-length part of the arguments. In the `average` function here,
it\'s done through an argument called `n_args.` In the `printf`
function, it\'s done with the format codes that you specify in that
first string in the arguments you provide.

Now that the function has been declared as using variable-length
arguments, we must next write the code that does the actual work in the
function. To access the numbers stored in the variable-length argument
list for our `average` function, we must first declare a variable for
the list itself:

``` c
  va_list myList;
```

The `va_list` type is a type declared in the `stdarg.h` header that
basically allows you to keep track of your list. To start actually using
`myList`, however, we must first assign it a value. After all, simply
declaring it by itself wouldn\'t do anything. To do this, we must call
`va_start`, which is actually a macro defined in `stdarg.h.` In the
arguments to `va_start`, you must provide the `va_list` variable you
plan on using, as well as the name of the last variable appearing before
the ellipsis in your function declaration:

``` c
#include <stdarg.h>
float average (int n_args, ...)
{
    va_list myList;
    va_start (myList, n_args);
    va_end (myList);
}
```

Now that `myList` has been prepped for usage, we can finally start
accessing the variables stored in it. To do so, use the `va_arg` macro,
which pops off the next argument on the list. In the arguments to
`va_arg`, provide the `va_list` variable you\'re using, as well as the
primitive data type (e.g. `int`, `char`) that the variable you\'re
accessing should be:

``` c
#include <stdarg.h>
float average (int n_args, ...)
{
    va_list myList;
    va_start (myList, n_args);

    int myNumber = va_arg (myList, int);
    va_end (myList);
}
```

By popping `n_args` integers off of the variable-length argument list,
we can manage to find the average of the numbers:

``` c
#include <stdarg.h>
float average (int n_args, ...)
{
    va_list myList;
    va_start (myList, n_args);

    int numbersAdded = 0;
    int sum = 0;

    while (numbersAdded < n_args) {
        int number = va_arg (myList, int); // Get next number from list
        sum += number;
        numbersAdded += 1;
    }
    va_end (myList);

    float avg = (float)(sum) / (float)(numbersAdded); // Find the average
    return avg;
}
```

By calling `average (2, 10, 20)`, we get the average of `10` and `20`,
which is `15.`

## References

fr:Programmation C/Fonctions et
procédures
it:C/Blocchi e
funzioni/Funzioni
pl:C/Funkcje


# C Programming/Standard libraries

The **C standard library** is a standardized collection of
s and library routines used to implement
common operations, such as input/output and character string handling.
Unlike other languages (such as COBOL, Fortran, and PL/I) C does not
include built in keywords for these tasks, so nearly all C programs rely
on the standard library to operate.

## History

The C programming language previously did not provide any elementary
functions, such as I/O operations. Over time, user communities of C
shared ideas and implementations to provide those functions. These ideas
became common, and were eventually incorporated into the definition of
the standardized C programming language in 1989. These are now called
the **C standard libraries**.

Both Unix and C were created at AT&T\'s Bell Laboratories in the late
1960s and early 1970s. During the 1970s the C programming language
became increasingly popular, with many universities and organizations
beginning to create their own variations of the language for their own
projects. By the start of the 1980s compatibility problems between the
various C implementations became apparent. In 1983 the American National
Standards Institute (ANSI) formed a committee to establish a standard
specification of C known as \"ANSI C\". This work culminated in the
creation of the so-called **C89** standard in 1989. Part of the
resulting standard was a set of software libraries called the **ANSI C
standard library**.

Later revisions of the C standard have added several new required header
files to the library. Support for these new extensions varies between
implementations.

The headers **\<iso646.h\>**, **\<wchar.h\>**, and **\<wctype.h\>** were
added with Normative Addendum 1 (hereafter abbreviated as **NA1**), an
addition to the C Standard ratified in 1995.

The headers **\<complex.h\>**, **\<fenv.h\>**, **\<inttypes.h\>**,
**\<stdbool.h\>**, **\<stdint.h\>**, and **\<tgmath.h\>** were added
with **C99**, a revision to the C Standard published in 1999.

## Design

The declaration of each function is kept in a header file, while the
actual implementation of functions are separated into a library file.
The naming and scope of headers have become common but the organization
of libraries still remains diverse. The standard library is usually
shipped along with a compiler. Since C compilers often provide extra
functions that are not specified in ANSI C, a standard library with a
particular compiler is mostly incompatible with standard libraries of
other compilers.

Much of the C standard library has been shown to have been
well-designed. A few parts, with the benefit of hindsight, are regarded
as mistakes. The string input functions `gets()` (and the use of
`scanf()` to read string input) are the source of many buffer overflows,
and most programming guides recommend avoiding this usage. Another
oddity is `strtok()`, a function that is designed as a primitive
lexical analyser but is highly
\"fragile\" and difficult to use.

## ANSI Standard

The ANSI C standard library consists of 24 C header files which can be
included into a programmer\'s project with a single directive. Each
header file contains one or more function declarations, data type
definitions and macros. The contents of these header files follows.

In comparison to some other languages (for example Java) the standard
library is minuscule. The library provides a basic set of mathematical
functions, string manipulation, type conversions, and file and
console-based I/O. It does not include a standard set of \"container
types\" like the C++ Standard Template Library, let alone the complete
graphical user interface (GUI) toolkits, networking tools, and profusion
of other functions that Java provides as standard. The main advantage of
the small standard library is that providing a working ANSI C
environment is much easier than it is with other languages, and
consequently porting C to a new platform is relatively easy.

Many other libraries have been developed to supply equivalent functions
to that provided by other languages in their standard library. For
instance, the GNOME desktop environment project has developed the GTK+
graphics toolkit and GLib, a library of container data structures, and
there are many other well-known examples. The variety of libraries
available has meant that some superior toolkits have proven themselves
through history. The considerable downside is that they often do not
work particularly well together, programmers are often familiar with
different sets of libraries, and a different set of them may be
available on any particular platform.

### ANSI C library header files

  ----------------------------------------------- -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
  **\<assert.h\>**       Contains the assert macro, used to assist with detecting logical errors and other types of bug in debugging versions of a program.
  **\<complex.h\>**     A set of functions for manipulating complex numbers. (New with **C99**)
  **\<ctype.h\>**         This header file contains functions used to classify characters by their types or to convert between upper and lower case in a way that is independent of the used character set (typically ASCII or one of its extensions, although implementations utilizing EBCDIC are also known).
  **\<errno.h\>**         For testing error codes reported by library functions.
  **\<fenv.h\>**           For controlling floating-point environment. (New with **C99**)
  **\<float.h\>**         Contains defined constants specifying the implementation-specific properties of the floating-point library, such as the minimum difference between two different floating-point numbers (\_EPSILON), the maximum number of digits of accuracy (\_DIG) and the range of numbers which can be represented (\_MIN, \_MAX).
  **\<inttypes.h\>**   For precise conversion between integer types. (New with **C99**)
  **\<iso646.h\>**       For programming in ISO 646 variant character sets. (New with **NA1**)
  **\<limits.h\>**       Contains defined constants specifying the implementation-specific properties of the integer types, such as the range of numbers which can be represented (\_MIN, \_MAX).
  **\<locale.h\>**       For setlocale() and related constants. This is used to choose an appropriate locale.
  **\<math.h\>**           For computing common mathematical functions \-- see ../Further math/ or C++ Programming/Code/Standard C Library/Math for details.
  **\<setjmp.h\>**       Declares the macros setjmp/longjmp\|setjmp and longjmp, which are used for non-local exits
  **\<signal.h\>**       For controlling various exceptional conditions
  **\<stdarg.h\>**       For accessing a varying number of arguments passed to functions.
  **\<stdbool.h\>**     For a boolean data type. (New with **C99**)
  **\<stdint.h\>**       For defining various integer types. (New with **C99**)
  **\<stddef.h\>**       For defining several useful types and macros.
  **\<stdio.h\>**         Provides the core input and output capabilities of the C language. This file includes the venerable `printf` function.
  **\<stdlib.h\>**       For performing a variety of operations, including conversion, pseudo-random numbers, memory allocation, process control, environment, signalling, searching, and sorting.
  **\<string.h\>**       For manipulating several kinds of strings.
  **\<tgmath.h\>**       For type-generic mathematical functions. (New with **C99**)
  **\<time.h\>**           For converting between various time and date formats.
  **\<wchar.h\>**         For manipulating wide streams and several kinds of strings using wide characters - key to supporting a range of languages. (New with **NA1**)
  **\<wctype.h\>**       For classifying wide characters. (New with **NA1**)
  ----------------------------------------------- -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

## Common support libraries

While not standardized, C programs may depend on a runtime library of
routines which contain code the compiler uses at runtime. The code that
initializes the process for the operating system, for example, before
calling `main()`, is implemented in the C Run-Time Library for a given
vendor\'s compiler. The Run-Time Library code might help with other
language feature implementations, like handling uncaught exceptions or
implementing floating point code.

The C standard library only documents that the specific routines
mentioned in this article are available, and how they behave. Because
the compiler implementation might depend on these additional
implementation-level functions to be available, it is likely the
vendor-specific routines are packaged with the C Standard Library in the
same module, because they\'re both likely to be needed by any program
built with their toolset.

Though often confused with the C Standard Library because of this
packaging, the C Runtime Library is not a standardized part of the
language and is vendor-specific.

## Compiler built-in functions

Some compilers (for example, GCC) provide built-in
versions of many of the functions in the C standard library; that is,
the implementations of the functions are written into the compiled
object file, and the program calls the built-in versions instead of the
functions in the C library shared object file. This reduces function
call overhead, especially if function calls are replaced with inline
variants, and allows other forms of optimization (as the compiler knows
the control-flow characteristics of the built-in variants), but may
cause confusion when debugging (for example, the built-in versions
cannot be replaced with instrumented variants).

## POSIX standard library

POSIX, (along with the Single Unix Specification), specifies a number of
routines that should be available over and above those in the C standard
library proper; these are often implemented alongside the C standard
library functions, with varying degrees of closeness. For example, glibc
implements functions such as fork within libc.so, but before NPTL was
merged into glibc it constituted a separate library with its own linker
flag. Often, this POSIX-specified function will be regarded as part of
the library; the C library proper may be identified as the ANSI or ISO C
library.

The following libraries are recognized by POSIX:

  ------------- -----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
  **c**         This option shall make available all interfaces referenced in the System Interfaces volume of POSIX.1-2008, with the possible exception of those interfaces listed as residing in \<aio.h\>, \<arpa/inet.h\>, \<complex.h\>, \<fenv.h\>, \<math.h\>, \<mqueue.h\>, \<netdb.h\>, \<net/if.h\>, \<netinet/in.h\>, \<pthread.h\>, \<sched.h\>, \<semaphore.h\>, \<spawn.h\>, \<sys/socket.h\>, pthread_kill(), and pthread_sigmask() in \<signal.h\>, \<trace.h\>, interfaces marked as optional in \<sys/mman.h\>, interfaces marked as ADV (Advisory Information) in \<fcntl.h\>, and interfaces beginning with the prefix clock\_ or time\_ in \<time.h\>. This option shall not be required to be present to cause a search of this library.
  **l**         This option shall make available all interfaces required by the C-language output of lex that are not made available through the -l c option. (The flex program, a clone of lex, uses fl instead of l.)
  **pthread**   This option shall make available all interfaces referenced in \<pthread.h\> and pthread_kill() and pthread_sigmask() referenced in \<signal.h\>. An implementation may search this library in the absence of this option.
  **m**         This option shall make available all interfaces referenced in \<math.h\>, \<complex.h\>, and \<fenv.h\>. An implementation may search this library in the absence of this option.
  **rt**        This option shall make available all interfaces referenced in \<aio.h\>, \<mqueue.h\>, \<sched.h\>, \<semaphore.h\>, and \<spawn.h\>, interfaces marked as optional in \<sys/mman.h\>, interfaces marked as ADV (Advisory Information) in \<fcntl.h\>, and interfaces beginning with the prefix clock\_ and time\_ in \<time.h\>. An implementation may search this library in the absence of this option.
  **trace**     This option shall make available all interfaces referenced in \<trace.h\>. An implementation may search this library in the absence of this option.
  **xnet**      This option shall make available all interfaces referenced in \<arpa/inet.h\>, \<netdb.h\>, \<net/if.h\>, \<netinet/in.h\>, and \<sys/socket.h\>. An implementation may search this library in the absence of this option.
  **y**         This option shall make available all interfaces required by the C-language output of yacc that are not made available through the -l c option. (Some clones of yacc, including bison and byacc, include the entire library in the generated file, so it is not necessary to use -l y.)
  ------------- -----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

## References

pl:C/Biblioteka standardowa


# C Programming/Beginning exercises

## Variables

### Naming

1.  Can a variable name start with a number?
2.  Can a variable name start with a typographical symbol(e.g. #, \*,
    \_)?
3.  Give an example of a C variable name that would *not* work. Why
    doesn\'t it work?

### Data Types

1.  List at least three data types in C
    1.  On your computer, how much memory does each require?
    2.  Which ones can be used in place of another? Why?
        1.  Are there any limitations on these uses?
        2.  If so, what are they?
        3.  Is it necessary to do anything special to use the
            alternative?
2.  Can the name we use for a data type (e.g. \'int\', \'float\') be
    used as a variable?

### Assignment

1.  How would you assign the value 3.14 to a variable called pi?
2.  Is it possible to assign an *int* to a *double*?
    1.  Is the reverse possible?

### Referencing

1.  A common mistake for new students is reversing the assignment
    statement. Suppose you want to assign the value stored in the
    variable \"pi\" to another variable, say \"pi2\":
    1.  What is the correct statement?
    2.  What is the reverse? Is this a valid C statement (even if it
        gives incorrect results)?
    3.  What if you wanted to assign a constant value (like 3.1415) to
        \"pi2\":

        :   **a**. What would the correct statement look like?
        :   **b**. Would the reverse be a valid or invalid C statement?

## Simple I/O

### String manipulation

1\. Write a program that prompts the user for a string (pick a maximum
length), and prints its reverse.

2\. Write a program that prompts the user for a sentence (again, pick a
maximum length), and prints each word on its own line.

### Loops

1\. Write a function that outputs a right isosceles triangle of height
and width *n*, so *n = 3* would look like

    *
    **
    ***

2\. Write a function that outputs a sideways triangle of height *2n-1*
and width *n*, so the output for *n = 4* would be:

    *
    **
    ***
    ****
    ***
    **
    *

3\. Write a function that outputs a right-side-up triangle of height *n*
and width *2n-1*; the output for *n = 6* would be:

         *
        ***
       *****
      *******
     *********
    ***********

## Program Flow

1\. Build a program where control passes from main to four different
functions with 4 calls.

2\. Now make a while loop in main with the function calls inside it. Ask
for input at the beginning of the loop. End the while loop if the user
hits Q

3\. Next add conditionals to call the functions when the user enters
numbers, so 1 goes to function1, 2 goes to function 2, etc.

4\. Have function 1 call function a, which calls function b, which calls
function c

5\. Draw out a diagram of program flow, with arrows to indicate where
control goes

## Functions

1\. Write a function to check if an integer is negative; the declaration
should look like bool is_positive(int i);

2\. Write a function to raise a floating point number to an integer
power, so for example to when you use it

``` c
float a = raise_to_power(2, 3);    //a gets 8
float b = raise_to_power(9, 2);    //b gets 81
float raise_to_power(float f, int power);    //make this your declaration
```

## Math

1\. Write a function to calculate if a number is prime. Return 1 if it
is prime and 0 if it is not a prime.

2\. Write a function to determine the number of prime numbers below n.

3\. Write a function to find the square root by using Newton\'s
method.

4\. Write functions to evaluate the trigonometric functions.

5\. Try to write a random number generator.

6\. Write a function to determine the prime number(s) between 2 and 100.

## Recursion

#### Merge sort

1\. Write a C program to generate a random integer array with a given
length n , and sort it recursively using the Merge sort algorithm.

-   The merge sort algorithm is a recursive algorithm .

\- sorting a one element array is easy.

\- sorting two one-element arrays, requires the merge operation. The
merge operation looks at two sorted arrays as lists, and compares the
head of the list , and which ever head is smaller, this element is put
on the sorted list and the head of that list is ticked off, so the next
element becomes the head of that list. This is done until one of the
lists is exhausted, and the other list is then copied onto the end of
the sorted list.

\- the recursion occurs, because merging two one-element arrays produces
one two-element sorted array, which can be merged with another
two-element sorted array produced the same way. This produces a sorted 4
element array, and the same applies for another 4 element sorted array.

\- so the basic merge sort, is to check the size of list to be sorted,
and if it is greater than one, divide the array into two, and call merge
sort again on the two halves. After wards, merge the two halves in a
temporary space of equal size, and then copy back the final sorted array
onto the original array.

#### Binary heaps

2\. **Binary heaps** :

-   A binary max-heap or min-heap, is an ordered structure where some
    nodes are guaranteed greater than other nodes, e.g. the parent vs
    two children. A binary heap can be stored in an array , where ,

\- given a position **i** (the parent) , **i\*2** is the left child, and
**i\*2+1** is the right child.

\- ( C arrays begin at position 0, but 0 \* 2 = 0, and 0 \*2 + 1= 1,
which is incorrect , so start the heap at position 1, or add 1 for
parent-to-child calculations, and subtract 1 for child-to-parent
calculations ).

-   try to model this using with a pencil and paper, using 10 random
    unsorted numbers, and inserting each of them into a \"heapsort\"
    array of 10 elements.

```{=html}
<!-- -->
```
-   To insert into a heap, **end-add** and **swap-parent** if higher,
    until parent higher.

```{=html}
<!-- -->
```
-   To delete the top of a heap, move **end-to-top**, and
    **defer-higher-child** or **sift-down** , until no child is higher.

```{=html}
<!-- -->
```
-   try it on a pen and paper the numbers 10, 4, 6 ,3 ,5 , 11.

```{=html}
<!-- -->
```
-   the answer was 11, 5, 10, 3, 4 , 6.

```{=html}
<!-- -->
```
-   EXERCISE: Now try removing each top element of 11, 5, 10, 3, 4, 6 ,
    using end-to-top and sift-down ( or swap-higher-child) to get the
    numbers

in descending order.

-   a priority queue allows elements to be inserted with a priority ,
    and extracted according to priority. ( This can happen usefully, if
    the element has a paired structure, one part is the key, and the
    other part the data. Otherwise, it is just a mechanism for sorting
    ).

```{=html}
<!-- -->
```
-   EXERCISE: Using the above technique of insert-back/challenge-parent,
    and delete-front/last-to-front/defer-higher-child, implement either
    heap sort or a priority queue.

#### Dijkstra\'s algorithm

Dijkstra\'s algorithm is a searching algorithm using a priority queue.
It begins with inserting the start node with a priority value of 0. All
other nodes are inserted with priority values of large N. Each node has
an adjacency list of other nodes, a current distance to start node, and
previous pointer to previous node used to calculate current node.
Alternative to an adjacency list, is an adjacency matrix, which needs n
x n boolean adjacencies.

The algorithm basically iterates over the priority queue, removing the
front node, examining the adjacent nodes, and updating with a distance
equal to the sum of the front nodes distance for each adjacent node ,
and the distance given by the adjacency information for an adjacent
node.

After each node\'s update, the extra operation **\"update priority\"**
is used on that node :

*while* the node\'s distance is less than it\'s parents node ( for this
priority queue, parents have lesser distances than the children), the
node is swapped with the parent.

After this, *while* the node is greater distance than one or more of its
children, it is swapped with the least distant child, so the least
distant child becomes parent of its greater distant sibling, and parent
to the greater distant current node.

With updating the priority, the adjacent node to the current node has a
back pointer changed to the current node.

The algorithm ends when the target node becomes the current node
removed, and the path to the start node can be recorded in an array by
following back pointers, and then doing something like a quick sort
partition to reverse the order of the array , to give the shortest path
to target node from the start node.

#### Quick sort

3\. Write a C program to recursively sort using the Quick sort partition
exchange algorithm.

-   you can use the \"driver\", or the random number test data from Q1.
    on mergesort. This is \"re-use\", which is encouraged in general.

\- an advantage of reuse is less writing time, debugging time, testing
time.

-   the concept of partition exchange is that a partition element is
    (randomly) selected, and every thing that needs sorted is put into 3
    equivalence

classes : those elements less than the partition value, the partition
element, and everything above (and equal to ) the partition element.

-   this can be done without allocating more space than one temporary
    element space for swapping two elements. e.g a temporary integer for
    integer data.
-   However, where the partition element should be using the original
    array space is not known.
-   This is usually implemented with putting the partition on the end of
    the array to be sorted, and then putting two pointers , one at the
    start of the array,

and one at the element next to the partition element , and repeatedly
scanning the left pointer right, and the right pointer left.

-   the left scan stops when an element equal to or greater than the
    partition is found, and the right scan stops for a smaller element
    than the partition value,

and these are swapped, which uses the temporary extra space.

-   the left scan will always stop if it reaches the partition element ,
    which is the last element; this means the entire array is less than
    partition value.
-   the right scan could reach the first element, if the entire array is
    greater than the partition , and this needs to be tested for, else
    the scan doesn\'t stop.
-   the outer loop exits when then left and right pointers cross.
    Testing for pointer crossing and outer loop exit

should occur before swapping, otherwise the right pointer may be
swapping a less-than-partition element previously scanned by the left
pointer.

-   finally, the partition element needs to be put between the left and
    right partitions, once the pointers cross.
-   At pointer crossing, the left pointer may be stopped at the
    partition element\'s last position in the array, and the right
    pointer not progressed past the

element just before the last element. This happens when all the elements
are less than the partition.

\- if the right pointer is chosen to swap with the partition, then an
incorrect state results where the last element of the left array becomes
less than the partition element value.

\- if the left pointer is chosen to swap with the partition, then the
left array will be less than the partition, and partition will have
swapped with an element with value greater than the partition or the
partition itself.

-   The corner case of quicksorting a 2 element
    `<b>`{=html}out-of-order`</b>`{=html} array has to be examined.

\- The left pointer stops on the first **out of order** element. The
right pointer begins on the first `<b>`{=html}out-of-order`</b>`{=html}
element, but the outer loop exits because this is the leftmost element.
The partition element is then swapped with the left pointer\'s first
element, and the two elements are now **in order**.

\- In the case of a 2 element **in order** array, the leftmost pointer
skips the first element which is less than the partition, and stops on
the partition. The right pointer begins on the first element and exits
because it is the first position. The pointers have crossed so the outer
loop exits. The partition swaps with itself, so the in-ordering is
preserved.

-   After doing a swap, the left pointer should be incremented and right
    pointer decremented, so the same positions aren\'t scanned again,
    because an endless loop can result ( possibly when the left pointer
    exits when the element is equal to or greater than the partition,
    and the right element is equal to the partition value). One
    implementation, Sedgewick, starts the pointers with the left pointer
    minus one and right pointer

the plus one the intended initial scan positions, and use the
pre-increment and pre-decrement operators e.g. ( ++i, \--i) .

fr:Exercices en langage C
et:Programmeerimiskeel
C/Harjutused
pl:C/Ćwiczenia dla
początkujących


# C Programming/Advanced data types

In the chapter Variables we looked at the
primitive data types. However *advanced* data types allow us greater
flexibility in managing data in our program.

## Structs

Structs are data types made of variables of other data types (possibly
including other structs). They are used to group pieces of information
into meaningful units, and also permit some constructs not possible
otherwise. The variables declared in a struct are called \"members\".
One defines a struct using the `struct` keyword. For example:

``` c
struct mystruct {
    int int_member;
    double double_member;
    char string_member[25];
} struct_var;
```

`struct_var` is a variable of type `struct mystruct`, which we declared
along with the definition of the new `struct mystruct` data type. More
commonly, struct variables are declared after the definition of the
struct, using the form:

``` c
struct mystruct struct_var;
```

It is often common practice to make a *type synonym* so we don\'t have
to type \"struct mystruct\" all the time. C allows us the possibility to
do so using a `typedef` statement, which aliases a type:

``` c
typedef struct {
    // ...
} Mystruct;
```

The `struct` itself is an *incomplete* type (by the absence of a name on
the first line), but it is aliased as `Mystruct`. Then the following may
be used:

``` c
Mystruct struct_var;
```

The members of a struct variable may be accessed using the member access
operator `.` (a dot) or the indirect member access operator `->` (an
arrow) if the struct variable is a pointer:

``` c
struct_var.int_member = 0;
struct_var->int_number = 0; // this statement is equivalent to: (*struct_var).int_number = 0;
```

(Pointers will be explained in the next chapter.) Structs may contain
not only their own variables but may also contain variables pointing to
other structs. This allows a recursive definition, which is very
powerful when used with pointers:

``` c
struct restaurant_order {
    char description[100];
    double price;
    struct restaurant_order *next_order;
};
```

This is an implementation of the linked list
data structure. Each node (a restaurant order) is pointing to one other
node. The linked list is terminated on the last node (in our example,
this would be the last order) whose `next_order` variable would be
assigned to `NULL`.

A recursive struct definition can be tricky when used with `typedef`. It
is not possible to declare a struct variable inside its own type by
using its aliased definition, since the aliased definition by `typedef`
does not exist before the `typedef` statement is evaluated:

``` c
typedef struct Mystruct {
    // ...
    struct Mystruct *pointer; // Mystruct *pointer; would cause a compile-time error
} Mystruct;
```

The size of a struct type is at least the sum of the sizes of all its
members. But a compiler is free to insert padding bytes between the
struct members to align the members to certain constraints. For example,
a struct containing of a char and a float will occupy 8 bytes on many
32bit architectures.

## Unions

The definition of a union is similar to that of a struct. The difference
between the two is that in a struct, the members occupy different areas
of memory, but in a union, the members occupy the same area of memory.
Thus, in the following type, for example:

``` c
union {
    int i;
    double d;
} u;
```

The programmer can access either `u.i` or `u.d`, but not both at the
same time. Since `u.i` and `u.d` occupy the same area of memory,
modifying one modifies the value of the other, sometimes in
unpredictable ways. This is also the main reason that unions are rarely
seen in practice.

The size of a union is the size of its largest member.

## Enumerations

Enumerations are artificial data types representing associations between
labels and integers. Unlike structs or unions, they are not composed of
other data types. An example declaration:

``` c
enum color {
    red,
    orange,
    yellow,
    green,
    cyan,
    blue,
    purple,
} crayon_color;
```

In the example above, red equals 0, orange equals 1, \... and so on. It
is possible to assign values to labels within the integer range, but
they must be a literal.

Similar declaration syntax that applies for structs and unions also
applies for enums. Also, one *normally* doesn\'t need to be concerned
with the integers that labels represent:

``` c
enum weather weather_outside = rain;
```

This peculiar property makes enums especially convenient in switch-case
statements:

``` c
enum weather {
    sunny,
    windy,
    cloudy,
    rain,
} weather_outside;

// ...

switch (weather_outside) {
case sunny:
    wear_sunglasses();
    break;
case windy:
    wear_windbreaker();
    break;
case cloudy:
    get_umbrella();
    break;
case rain:
    get_umbrella();
    wear_raincoat();
    break;
}
```

Enums are a simplified way to emulate associative arrays in C.

de:C-Programmierung: Komplexe
Datentypen
fr:Programmation C/Types
avancés pl:C/Typy
złożone