# C Programming/Further math

The `<math.h>` header contains prototypes for several functions that
deal with mathematics. In the 1990 version of the ISO standard, only the
`double` versions of the functions were specified; the 1999 version
added the `float` and `long double` versions. To use these math
functions, you must link your program with the math library. For some
compilers (including GCC), you must specify the additional parameter
`-lm`[^1][^2].

The math functions may produce one of two kinds of errors. *Domain
errors* occur when the parameters to the functions are invalid, such as
a negative number as a parameter to `sqrt` (the square root function).
*Range errors* occur when the result of the function cannot be expressed
in that particular floating-point type, such as `pow(1000.0, 1000.0)` if
the maximum value of a double is around 10^308^.

The functions can be grouped into the following categories:

## Trigonometric functions

### The `acos` and `asin` functions

The `acos` functions return the arccosine of their arguments in radians,
and the `asin` functions return the arcsine of their arguments in
radians. All functions expect the argument in the range \[-1,+1\]. The
arccosine returns a value in the range \[0,π\]; the arcsine returns a
value in the range \[-π/2,+π/2\].

``` c
 #include <math.h>
 float asinf(float x); /* C99 */
 float acosf(float x); /* C99 */
 double asin(double x);
 double acos(double x);
 long double asinl(long double x); /* C99 */
 long double acosl(long double x); /* C99 */
```

### The `atan` and `atan2` functions

The `atan` functions return the arctangent of their arguments in
radians, and the `atan2` function return the arctangent of `y/x` in
radians. The `atan` functions return a value in the range \[-π/2,+π/2\]
(the reason why ±π/2 are included in the range is because the
floating-point value may represent infinity, and atan(±∞) = ±π/2); the
`atan2` functions return a value in the range \[-π,+π\]. For `atan2`, a
domain error may occur if both arguments are zero.

``` c
 #include <math.h>
 float atanf(float x); /* C99 */
 float atan2f(float y, float x); /* C99 */
 double atan(double x);
 double atan2(double y, double x);
 long double atanl(long double x); /* C99 */
 long double atan2l(long double y, long double x); /* C99 */
```

### The `cos`, `sin`, and `tan` functions

The `cos`, `sin`, and `tan` functions return the cosine, sine, and
tangent of the argument, expressed in radians.

``` c
 #include <math.h>
 float cosf(float x); /* C99 */
 float sinf(float x); /* C99 */
 float tanf(float x); /* C99 */
 double cos(double x);
 double sin(double x);
 double tan(double x);
 long double cosl(long double x); /* C99 */
 long double sinl(long double x); /* C99 */
 long double tanl(long double x); /* C99 */
```

## Hyperbolic functions

The `cosh`, `sinh` and `tanh` functions compute the hyperbolic cosine,
the hyperbolic sine, and the hyperbolic tangent of the argument
respectively. For the hyperbolic sine and cosine functions, a range
error occurs if the magnitude of the argument is too large.

The `acosh` functions compute the inverse hyperbolic cosine of the
argument. A domain error occurs for arguments less than 1.

The `asinh` functions compute the inverse hyperbolic sine of the
argument.

The `atanh` functions compute the inverse hyperbolic tangent of the
argument. A domain error occurs if the argument is not in the interval
\[-1, +1\]. A range error may occur if the argument equals -1 or +1.

``` c
 #include <math.h>
 float coshf(float x); /* C99 */
 float sinhf(float x); /* C99 */
 float tanhf(float x); /* C99 */
 double cosh(double x);
 double sinh(double x);
 double tanh(double x);
 long double coshl(long double x); /* C99 */
 long double sinhl(long double x); /* C99 */
 long double tanhl(long double x); /* C99 */
 float acoshf(float x); /* C99 */
 float asinhf(float x); /* C99 */
 float atanhf(float x); /* C99 */
 double acosh(double x); /* C99 */
 double asinh(double x); /* C99 */
 double atanh(double x); /* C99 */
 long double acoshl(long double x); /* C99 */
 long double asinhl(long double x); /* C99 */
 long double atanhl(long double x); /* C99 */
```

## Exponential and logarithmic functions

### The `exp`, `exp2`, and `expm1` functions

The `exp` functions compute the base-*e* exponential function of `x`
(*e*^x^). A range error occurs if the magnitude of `x` is too large.

The `exp2` functions compute the base-2 exponential function of `x`
(2^x^). A range error occurs if the magnitude of `x` is too large.

The `expm1` functions compute the base-*e* exponential function of the
argument, minus 1. A range error occurs if the magnitude of `x` is too
large.

``` c
 #include <math.h>
 float expf(float x); /* C99 */
 double exp(double x);
 long double expl(long double x); /* C99 */
 float exp2f(float x); /* C99 */
 double exp2(double x); /* C99 */
 long double exp2l(long double x); /* C99 */
 float expm1f(float x); /* C99 */
 double expm1(double x); /* C99 */
 long double expm1l(long double x); /* C99 */
```

### The `frexp`, `ldexp`, `modf`, `scalbn`, and `scalbln` functions

These functions are heavily used in software floating-point emulators,
but are otherwise rarely directly called.

Inside the computer, each floating point number is represented by two
parts:

-   The significand is either in the range \1/2, 1), or it equals zero.
-   The exponent is an integer.

The value of a floating point number $v$ is
$v = {\rm significand} \times 2^{\rm exponent}$.

The `frexp` functions break the argument floating point number `value`
into those two parts, the exponent and significand. After breaking it
apart, it stores the exponent in the `int` object pointed to by `ex`,
and returns the significand. In other words, the value returned is a
copy of the given floating point number but with an exponent replaced by
0. If `value` is zero, both parts of the result are zero.

The `ldexp` functions multiply a floating-point number by a integral
power of 2 and return the result. In other words, it returns copy of the
given floating point number with the exponent increased by ex. A range
error may occur.

The `modf` functions break the argument `value` into integer and
fraction parts, each of which has the same sign as the argument. They
store the integer part in the object pointed to by `*iptr` and return
the fraction part. The `*iptr` is a floating-point type, rather than an
\"int\" type, because it might be used to store an integer like 1 000
000 000 000 000 000 000 which is too big to fit in an int.

The `scalbn` and `scalbln` compute `x` × `FLT_RADIX`^`n`^. `FLT_RADIX`
is the base of the floating-point system; if it is 2, the functions are
equivalent to `ldexp`.

``` c
 #include <math.h>
 float frexpf(float value, int *ex); /* C99 */
 double frexp(double value, int *ex);
 long double frexpl(long double value, int *ex); /* C99 */
 float ldexpf(float x, int ex); /* C99 */
 double ldexp(double x, int ex);
 long double ldexpl(long double x, int ex); /* C99 */
 float modff(float value, float *iptr); /* C99 */
 double modf(double value, double *iptr);
 long double modfl(long double value, long double *iptr); /* C99 */
 float scalbnf(float x, int ex); /* C99 */
 double scalbn(double x, int ex); /* C99 */
 long double scalbnl(long double x, int ex); /* C99 */
 float scalblnf(float x, long int ex); /* C99 */
 double scalbln(double x, long int ex); /* C99 */
 long double scalblnl(long double x, long int ex); /* C99 */
```

Most C floating point libraries also implement the IEEE754-recommended
nextafter(), nextUp( ), and nextDown( ) functions.
[3

### The `log`, `log2`, `log1p`, and `log10` functions

The `log` functions compute the base-*e* natural logarithm of the
argument and return the result. A domain error occurs if the argument is
negative. A range error may occur if the argument is zero.

The `log1p` functions compute the base-*e* natural logarithm of one plus
the argument and return the result. A domain error occurs if the
argument is less than -1. A range error may occur if the argument is -1.

The `log10` functions compute the common (base-10) logarithm of the
argument and return the result. A domain error occurs if the argument is
negative. A range error may occur if the argument is zero.

The `log2` functions compute the base-2 logarithm of the argument and
return the result. A domain error occurs if the argument is negative. A
range error may occur if the argument is zero.

``` c
 #include <math.h>
 float logf(float x); /* C99 */
 double log(double x);
 long double logl(long double x); /* C99 */
 float log1pf(float x); /* C99 */
 double log1p(double x); /* C99 */
 long double log1pl(long double x); /* C99 */
 float log10f(float x); /* C99 */
 double log10(double x);
 long double log10l(long double x); /* C99 */
 float log2f(float x); /* C99 */
 double log2(double x); /* C99 */
 long double log2l(long double x); /* C99 */
```

### The `ilogb` and `logb` functions

The `ilogb` functions extract the exponent of `x` as a signed int value.
If `x` is zero, they return the value `FP_ILOGB0`; if `x` is infinite,
they return the value `INT_MAX`; if `x` is not-a-number they return the
value `FP_ILOGBNAN`; otherwise, they are equivalent to calling the
corresponding `logb` function and casting the returned value to type
`int`. A range error may occur if `x` is zero. `FP_ILOGB0` and
`FP_ILOGBNAN` are macros defined in `math.h`; `INT_MAX` is a macro
defined in `limits.h`.

The `logb` functions extract the exponent of `x` as a signed integer
value in floating-point format. If `x` is subnormal, it is treated as if
it were normalized; thus, for positive finite `x`, 1 ≤ `x` ×
`FLT_RADIX`^`-logb(x)`^ \< `FLT_RADIX` . `FLT_RADIX` is the radix for
floating-point numbers, defined in the `float.h` header.

``` c
 #include <math.h>
 int ilogbf(float x); /* C99 */
 int ilogb(double x); /* C99 */
 int ilogbl(long double x); /* C99 */
 float logbf(float x); /* C99 */
 double logb(double x); /* C99 */
 long double logbl(long double x); /* C99 */
```

## Power functions

### The `pow` functions

The `pow` functions compute `x` raised to the power `y` and return the
result. A domain error occurs if `x` is negative and `y` is not an
integral value. A domain error occurs if the result cannot be
represented when `x` is zero and `y` is less than or equal to zero. A
range error may occur.

``` c
 #include <math.h>
 float powf(float x, float y); /* C99 */
 double pow(double x, double y);
 long double powl(long double x, long double y); /* C99 */
```

### The `sqrt` functions

The `sqrt` functions compute the positive square root of `x` and return
the result. A domain error occurs if the argument is negative.

``` c
 #include <math.h>
 float sqrtf(float x); /* C99 */
 double sqrt(double x);
 long double sqrtl(long double x); /* C99 */
```

### The `cbrt` functions

The `cbrt` functions compute the cube root of `x` and return the result.

``` c
 #include <math.h>
 float cbrtf(float x); /* C99 */
 double cbrt(double x); /* C99 */
 long double cbrtl(long double x); /* C99 */
```

### The `hypot` functions

The `hypot` functions compute the square root of the sums of the squares
of `x` and `y`, without overflow or underflow, and return the result.

``` c
 #include <math.h>
 float hypotf(float x, float y); /* C99 */
 double hypot(double x, double y); /* C99 */
 long double hypotl(long double x, long double y); /* C99 */
```

## Nearest integer, absolute value, and remainder functions

### The `ceil` and `floor` functions

The `ceil` functions compute the smallest integral value not less than
`x` and return the result; the `floor` functions compute the largest
integral value not greater than `x` and return the result.

``` c
 #include <math.h>
 float ceilf(float x); /* C99 */
 double ceil(double x);
 long double ceill(long double x); /* C99 */
 float floorf(float x); /* C99 */
 double floor(double x);
 long double floorl(long double x); /* C99 */
```

### The `fabs` functions

The `fabs` functions compute the absolute value of a floating-point
number `x` and return the result.

``` c
 #include <math.h>
 float fabsf(float x); /* C99 */
 double fabs(double x);
 long double fabsl(long double x); /* C99 */
```

### The `fmod` functions

The `fmod` functions compute the floating-point remainder of `x/y` and
return the value `x` - *i* \* `y`, for some integer *i* such that, if
`y` is nonzero, the result has the same sign as `x` and magnitude less
than the magnitude of `y`. If `y` is zero, whether a domain error occurs
or the `fmod` functions return zero is implementation-defined.

``` c
 #include <math.h>
 float fmodf(float x, float y); /* C99 */
 double fmod(double x, double y);
 long double fmodl(long double x, long double y); /* C99 */
```

### The `nearbyint`, `rint`, `lrint`, and `llrint` functions

The `nearbyint` functions round their argument to an integer value in
floating-point format, using the current rounding direction and without
raising the \"inexact\" floating-point exception.

The `rint` functions are similar to the `nearbyint` functions except
that they can raise the \"inexact\" floating-point exception if the
result differs in value from the argument.

The `lrint` and `llrint` functions round their arguments to the nearest
integer value according to the current rounding direction. If the result
is outside the range of values of the return type, the numeric result is
undefined and a range error may occur if the magnitude of the argument
is too large.

``` c
 #include <math.h>
 float nearbyintf(float x); /* C99 */
 double nearbyint(double x); /* C99 */
 long double nearbyintl(long double x); /* C99 */
 float rintf(float x); /* C99 */
 double rint(double x); /* C99 */
 long double rintl(long double x); /* C99 */
 long int lrintf(float x); /* C99 */
 long int lrint(double x); /* C99 */
 long int lrintl(long double x); /* C99 */
 long long int llrintf(float x); /* C99 */
 long long int llrint(double x); /* C99 */
 long long int llrintl(long double x); /* C99 */
```

### The `round`, `lround`, and `llround` functions

The `round` functions round the argument to the nearest integer value in
floating-point format, rounding halfway cases away from zero, regardless
of the current rounding direction.

The `lround` and `llround` functions round the argument to the nearest
integer value, rounding halfway cases away from zero, regardless of the
current rounding direction. If the result is outside the range of values
of the return type, the numeric result is undefined and a range error
may occur if the magnitude of the argument is too large.

``` c
 #include <math.h>
 float roundf(float x); /* C99 */
 double round(double x); /* C99 */
 long double roundl(long double x); /* C99 */
 long int lroundf(float x); /* C99 */
 long int lround(double x); /* C99 */
 long int lroundl(long double x); /* C99 */
 long long int llroundf(float x); /* C99 */
 long long int llround(double x); /* C99 */
 long long int llroundl(long double x); /* C99 */
```

### The `trunc` functions

The `trunc` functions round their argument to the integer value in
floating-point format that is nearest but no larger in magnitude than
the argument.

``` c
 #include <math.h>
 float truncf(float x); /* C99 */
 double trunc(double x); /* C99 */
 long double truncl(long double x); /* C99 */
```

### The `remainder` functions

The `remainder` functions compute the remainder `x` REM `y` as defined
by IEC 60559. The definition reads, \"When *y* ≠ 0, the remainder *r* =
*x* REM *y* is defined regardless of the rounding mode by the
mathematical reduction *r* = *x* - *ny*, where *n* is the integer
nearest the exact value of *x*/*y*; whenever \|*n* - *x*/*y*\| = ½, then
*n* is even. Thus, the remainder is always exact. If *r* = 0, its sign
shall be that of *x*.\" This definition is applicable for all
implementations.

``` c
 #include <math.h>
 float remainderf(float x, float y); /* C99 */
 double remainder(double x, double y); /* C99 */
 long double remainderl(long double x, long double y); /* C99 */
```

### The `remquo` functions

The `remquo` functions return the same remainder as the `remainder`
functions. In the object pointed to by `quo`, they store a value whose
sign is the sign of `x`/`y` and whose magnitude is congruent modulo 2^n^
to the magnitude of the integral quotient of `x`/`y`, where *n* is an
implementation-defined integer greater than or equal to 3.

``` c
 #include <math.h>
 float remquof(float x, float y, int *quo); /* C99 */
 double remquo(double x, double y, int *quo); /* C99 */
 long double remquol(long double x, long double y, int *quo); /* C99 */
```

## Error and gamma functions

The `erf` functions compute the error function of the argument
$\frac{2}{\sqrt{\pi}}\int_{0}^x e^{-t^2}\,\mathrm dt$

The `erfc` functions compute the complimentary error function of the
argument (that is, 1 - erf x). For the `erfc` functions, a range error
may occur if the argument is too large.

The `lgamma` functions compute the natural logarithm of the absolute
value of the gamma of the argument (that is, log~*e*~\|Γ(x)\|). A range
error may occur if the argument is a negative integer or zero.

The `tgamma` functions compute the gamma of the argument (that is,
Γ(x)). A domain error occurs if the argument is a negative integer or if
the result cannot be represented when the argument is zero. A range
error may occur.

``` c
 #include <math.h>
 float erff(float x); /* C99 */
 double erf(double x); /* C99 */
 long double erfl(long double x); /* C99 */
 float erfcf(float x); /* C99 */
 double erfc(double x); /* C99 */
 long double erfcl(long double x); /* C99 */
 float lgammaf(float x); /* C99 */
 double lgamma(double x); /* C99 */
 long double lgammal(long double x); /* C99 */
 float tgammaf(float x); /* C99 */
 double tgamma(double x); /* C99 */
 long double tgammal(long double x); /* C99 */
```

## References

{{-}}

fr:Programmation
C/Mathématiques
pl:C/Zaawansowane operacje
matematyczne

[^1]: 1
    Why do you have to link the math library in C?

[^2]: 2
    Why do I have to explicitly link with libm?


# C Programming/Libraries

A *library* in C is a collection of header files, exposed for use by
other programs. The library therefore consists of an *interface*
expressed in a `.h` file (named the \"header\") and an *implementation*
expressed in a `.c` file. This `.c` file might be precompiled or
otherwise inaccessible, or it might be available to the programmer.
(Note: Libraries may call functions in other libraries such as the
Standard C or math libraries to do various tasks.)

The format of a library varies with the operating system and compiler
one is using. For example, in the Unix and Linux operating systems, a
library consists of one or more *object files*, which consist of object
code that is usually the output of a compiler (if the source language is
C or something similar) or an assembler (if the source language is
assembly language). These object files are then turned into a library in
the form of an archive by the *ar* archiver (a program that takes files
and stores them in a bigger file without regard to compression). The
filename for the library usually starts with \"lib\" and ends with
\".a\"; e.g. the *libc.a* file contains the Standard C library and the
\"libm.a\" the mathematics routines, which the linker would then link
in. Other operating systems such as Microsoft Windows use a \".lib\"
extension for libraries and an \".obj\" extension for object files. Some
programs in the Unix environment such as lex and yacc generate C code
that can be linked with the libl and liby libraries to create an
executable.

We\'re going to use as an example a library that contains one function:
a function to parse arguments from the command
line. Arguments on the command line could be by themselves:

`    -i`

have an optional argument that is
concatenated to the letter:

`    -ioptarg`

or have the argument in a separate argv-element:

`    -i optarg`

The library also has four declarations that it exports in addition to
the function: three integers and a pointer to the optional argument. If
the argument does not have an optional argument, the pointer to the
optional argument will be null.

In order to parse all these types of arguments, we have written the
following \"getopt.c\" file:

``` c
#include <stdio.h>              /* for fprintf() and EOF */
#include <string.h>             /* for strchr() */
#include "getopt.h"             /* consistency check */

/* variables */
int opterr = 1;                 /* getopt prints errors if this is on */
int optind = 1;                 /* token pointer */
int optopt;                     /* option character passed back to user */
char *optarg;                   /* flag argument (or value) */

/* function */
/* return option character, EOF if no more or ? if problem.
    The arguments to the function:
    argc, argv - the arguments to the main() function. An argument of "--"
    stops the processing.
    opts - a string containing the valid option characters.
    an option character followed by a colon (:) indicates that
    the option has a required argument.
*/
int
getopt (int argc, char **argv, char *opts)
{
    static int sp = 1;            /* character index into current token */
    register char *cp;            /* pointer into current token */

    if (sp == 1)
    {
        /* check for more flag-like tokens */
        if (optind >= argc || argv[optind][0] != '-' || argv[optind][1] == '\0')
            return EOF;
        else if (strcmp (argv[optind], "--") == 0)
        {
            optind++;
            return EOF;
        }
    }

    optopt = argv[optind][sp];

    if (optopt == ':' || (cp = strchr (opts, optopt)) == NULL)
    {
        if (opterr)
            fprintf (stderr, "%s: invalid option -- '%c'\n", argv[0], optopt);

        /* if no characters left in this token, move to next token */
        if (argv[optind][++sp] == '\0')
        {
            optind++;
            sp = 1;
        }

        return '?';
    }

    if (*++cp == ':')
    {
        /* if a value is expected, get it */
        if (argv[optind][sp + 1] != '\0')
            /* flag value is rest of current token */
            optarg = argv[optind++] + (sp + 1);
        else if (++optind >= argc)
        {
            if (opterr)
                fprintf (stderr, "%s: option requires an argument -- '%c'\n",
                            argv[0], optopt);
            sp = 1;
            return '?';
        }
        else
                    /* flag value is next token */
                optarg = argv[optind++];
        sp = 1;
    }
    else
    {
        /* set up to look at next char in token, next time */
        if (argv[optind][++sp] == '\0')
        {
            /* no more in current token, so setup next token */
            sp = 1;
            optind++;
        }
        optarg = 0;
    }
    return optopt;
}
/* END OF FILE */
```

The interface would be the following \"getopt.h\" file:

``` c
#ifndef GETOPT_H
    #define GETOPT_H

    /* exported variables */
    extern int opterr, optind, optopt;
    extern char *optarg;

    /* exported function */
    int getopt(int, char **, char *);
#endif

/* END OF FILE */
```

At a minimum, a programmer has the interface file to figure out how to
use a library, although, in general, the library programmer also wrote
documentation on how to use the library. In the above case, the
documentation should say that the provided arguments `**argv` and
`*opts` both shouldn\'t be null pointers (or why would you be using the
`getopt` function anyway?). Specifically, it typically states what each
parameter is for and what return values can be expected in which
conditions. Programmers that use a library, are normally not interested
in the implementation of the library \-- unless the implementation has a
bug, in which case he would want to complain somehow.

Both the implementation of the getopts library, and programs that use
the library should state `#include "getopt.h"`, in order to refer to the
corresponding interface. Now the library is \"linked\" to the program
\-- the one that contains the main() function. The program may refer to
dozens of interfaces.

In some cases, just placing `#include "getopt.h"` may appear correct but
will still fail to link properly. This indicates that the library is not
installed correctly, or there may be some additional configuration
required. You will have to check either the compiler\'s documentation or
library\'s documentation on how to resolve this issue.

## What to put in header files

As a general rule, headers should contain any declarations and macro
definitions (preprocessor `#define`s) to be \"seen\" by the other
modules in a program.

Possible declarations:

-   struct, union, and enum declarations
-   typedef declarations
-   external function declarations
-   global variable declarations

In the above `getopt.h` example file, one function (`getopt`) is
declared and four global variables (`optind`, `optopt`, `optarg`, and
`opterr`) are also declared. The variables are declared with the storage
class specifier `extern` in the header file because that keyword
specifies that the \"real\" variables are stored elsewhere (i.e. the
`getopt.c` file) and not within the header file.

The `#ifndef GETOPT_H/#define GETOPT_H` trick is colloquially called
`<b>`{=html}include guards`</b>`{=html}. This is used so that if the
`getopt.h` file were included more than once in a translation unit, the
unit would only see the contents once. Alternatively,
`#pragma once` in a header file can also be
used to achieve the same thing in some compilers (`#pragma` is an
unportable catchall).

## Linking Libraries Into Executables

Linking libraries into executables varies by operating system and
compiler/linker used. In Unix, directories of linked object files can be
specified with the `-L` option to the cc command and individual
libraries are specified with the `-l` (small ell) option. The `-lm`
option specifies that the libm math library should be linked in, for
example.

## References

-   C FAQ: \"I\'m wondering what to put in .c files and what to put in
    .h files. (What does \".h\" mean,
    anyway?)\"
-   PIClist thread: \"Global variables in projects with many C
    files.\"
-   \"How do I use extern to share variables between source files in
    C?\".

fr:Programmation C/Bibliothèque
standard
pl:C/Biblioteki


# C Programming/Common practices

With its extensive use, a number of common practices and conventions
have evolved to help avoid errors in C programs. These are
simultaneously a demonstration of the application of good software
engineering principles to a language and an indication of the
limitations of C. Although few are used universally, and some are
controversial, each of these enjoys wide use.

## Dynamic multidimensional arrays

Although one-dimensional arrays are easy to create dynamically using
malloc, and fixed-size multidimensional arrays are easy to create using
the built-in language feature, dynamic multidimensional arrays are
trickier. There are a number of different ways to create them, each with
different tradeoffs. The two most popular ways to create them are:

-   They can be allocated as a single block of memory, just like static
    multidimensional arrays. This requires that the array be
    *rectangular* (i.e. subarrays of lower dimensions are static and
    have the same size). The disadvantage is that the syntax of
    declaration the pointer is a little tricky for programmers at first.
    For example, if one wanted to create an array of ints of 3 columns
    and `rows` rows, one would do

``` c
int (*multi_array)[3] = malloc(rows * sizeof(int[3]));
```

:   (Note that here `multi_array` is a pointer to an array of 3 ints.)

```{=html}
<!-- -->
```

:   Because of array-pointer interchangeability, you can index this just
    like static multidimensional arrays, i.e. `multi_array[5][2]` is the
    element at the 6th row and 3rd column.

-   Dynamic multidimensional arrays can be allocated by first allocating
    an array of pointers, and then allocating subarrays and storing
    their addresses in the array of pointers.`<ref>`{=html}

Adam N. Rosenberg. \"A Description of One Programmer's Programming
Style Revisited\".
2001. p. 19-20.

```{=html}
</ref>
```
(This approach is also known as an Iliffe
vector). The syntax for accessing elements
is the same as for multidimensional arrays described above (even though
they are stored very differently). This approach has the advantage of
the ability to make ragged arrays (i.e. with subarrays of different
sizes). However, it also uses more space and requires more levels of
indirection to index into, and can have worse cache performance. It also
requires many dynamic allocations, each of which can be expensive.

For more information, see the comp.lang.c FAQ, question
6.16.

In some cases, the use of multi-dimensional arrays can best be addressed
as an array of structures. Before user-defined data structures were
available, a common technique was to define a multi-dimensional array,
where each column contained different information about the row. This
approach is also frequently used by beginner programmers. For example,
columns of a two-dimensional character array might contain last name,
first name, address, etc.

In cases like this, it is better to define a structure that contains the
information that was stored in the columns, and then create an array of
pointers to that structure. This is especially true when the number of
data points for a given record might vary, such as the tracks on an
album. In these cases, it is better to create a structure for the album
that contains information about the album, along with a dynamic array
for the list of songs on the album. Then an array of pointers to the
album structure can be used to store the collection.

-   Another useful way to create a dynamic multi-dimensional array is to
    flatten the array and index manually. For example, a 2-dimensional
    array with sizes x and y has x\*y elements, therefore can be created
    by

``` c
int dynamic_multi_array[x*y];
```

The index is slightly trickier than before, but can still be obtained by
y\*i+j. You then access the array with

``` c
static_multi_array[i][j];
dynamic_multi_array[y*i+j];
```

Some more examples with higher dimensions:

``` c
int dim1[w];
int dim2[w*x];
int dim3[w*x*y];
int dim4[w*x*y*z];

dim1[i]
dim2[w*j+i];
dim3[w*(x*i+j)+k] // index is k + w*j + w*x*i
dim4[w*(x*(y*i+j)+k)+l] // index is w*x*y*i + w*x*j + w*k + l
```

Note that w\*(x\*(y\*i+j)+k)+l is equal to w\*x\*y\*i + w\*x\*j + w\*k +
l, but uses fewer operations (see Horner\'s
Method). It uses the
same number of operations as accessing a static array by
dim4\[i\]\[j\]\[k\]\[l\], so should not be any slower to use.

The advantage to using this method is that the array can be passed
freely between functions without knowing the size of the array at
compile time (since C sees it as a 1-dimensional array, although some
way of passing the dimensions is still necessary), and the entire array
is contiguous in memory, so accessing consecutive elements should be
fast. The disadvantage is that it can be difficult at first to get used
to how to index the elements.

## Constructors and destructors

In most object-oriented languages, objects cannot be created directly by
a client that wishes to use them. Instead, the client must ask the class
to build an instance of the object using a special routine called a
constructor. Constructors are important because they allow an object to
enforce invariants about its internal state throughout its lifetime.
Destructors, called at the end of an object\'s lifetime, are important
in systems where an object holds exclusive access to some resource, and
it is desirable to ensure that it releases these resources for use by
other objects.

Since C is not an object-oriented language, it has no built-in support
for constructors or destructors. It is not uncommon for clients to
explicitly allocate and initialize records and other objects. However,
this leads to a potential for errors, since operations on the object may
fail or behave unpredictably if the object is not properly initialized.
A better approach is to have a function that creates an instance of the
object, possibly taking initialization parameters, as in this example:

``` c
struct string {
    size_t size;
    char *data;
};

struct string *create_string(const char *initial) {
    assert (initial != NULL);
    struct string *new_string = malloc(sizeof(*new_string));
    if (new_string != NULL) {
        new_string->size = strlen(initial);
        new_string->data = strdup(initial);
    }
    return new_string;
}
```

Similarly, if it is left to the client to destroy objects correctly,
they may fail to do so, causing resource leaks. It is better to have an
explicit destructor which is always used, such as this one:

``` c
void free_string(struct string *s) {
    assert (s != NULL);
    free(s->data);  ''/* free memory held by the structure */''
    free(s);        ''/* free the structure itself */''
}
```

It is often useful to combine destructors with *#Nulling freed
pointers*.

Sometimes it is useful to hide the definition of the object to ensure
that the client does not allocate it manually. To do this, the structure
is defined in the source file (or a private header file not available to
users) instead of the header file, and a forward declaration is put in
the header file:

``` c
struct string;
struct string *create_string(const char *initial);
void free_string(struct string *s);
```

## Nulling freed pointers

As discussed earlier, after `free()` has been called on a pointer, it
becomes a dangling pointer. Worse still, most modern platforms cannot
detect when such a pointer is used before being reassigned.

One simple solution to this is to ensure that any pointer is set to a
null pointer immediately after being freed: [^1]

``` c
free(p);
p = NULL;
```

Unlike dangling pointers, a hardware exception will arise on many modern
architectures when a null pointer is dereferenced. Also, programs can
include error checks for the null value, but not for a dangling pointer
value. To ensure it is done at all locations, a macro can be used:

``` c
#define FREE(p)   do { free(p); (p) = NULL; } while(0)
```

(To see why the macro is written this way, see *#Macro
conventions*.) Also, when this technique
is used, destructors should zero out the pointer that they are passed,
and their argument must be passed by reference to allow this. For
example, here\'s the destructor from *#Constructors and
destructors* updated:

``` c
void free_string(struct string **s) {
    assert(s != NULL  &&  *s != NULL);
    FREE((*s)->data);  ''/* free memory held by the structure */''
    FREE(*s);          ''/* free the structure itself */''
    *s=NULL;           ''/* zero the argument */''
}
```

Unfortunately, this idiom will not do anything to any other pointers
that may be pointing to the freed memory. For this reason, some C
experts regard this idiom as dangerous due to creating a false sense of
security.

## Macro conventions

Because preprocessor macros in C work using simple token replacement,
they are prone to a number of confusing errors, some of which can be
avoided by following a simple set of conventions:

1.  Placing parentheses around macro arguments wherever possible. This
    ensures that, if they are expressions, the order of operations does
    not affect the behavior of the expression. For example:
    -   Wrong: `#define square(x) x*x`
    -   Better: `#define square(x) (x)*(x)`
2.  Placing parentheses around the entire expression if it is a single
    expression. Again, this avoids changes in meaning due to the order
    of operations.
    -   Wrong: `#define square(x) (x)*(x)`
    -   Better: `#define square(x) ((x)*(x))`
    -   Dangerous, remember it replaces the text in verbatim. Suppose
        your code is `square (x++)`, after the macro invocation will x
        be incremented by 2
3.  If a macro produces multiple statements, or declares variables, it
    can be wrapped in a **do** { \... } **while**(0) loop, with no
    terminating semicolon. This allows the macro to be used like a
    single statement in any location, such as the body of an if
    statement, while still allowing a semicolon to be placed after the
    macro invocation without creating a null statement.`<ref>`{=html}

\"comp.lang.c FAQ: What\'s the best way to write a multi-statement
macro?\".

```{=html}
</ref>
```
[^2][^3][^4][^5][^6] Care must be taken that any new variables do not
potentially mask portions of the macro\'s arguments.

#\*Wrong: `#define FREE(p) free(p); p = NULL;`

#\*Better: `#define FREE(p) do { free(p); p = NULL; } while(0)`

1.  Avoiding using a macro argument twice or more inside a macro, if
    possible; this causes problems with macro arguments that contain
    side effects, such as assignments.
2.  If a macro may be replaced by a function in the future, considering
    naming it like a function.
3.  By convention, preprocessor values and macros defined by `#define`
    are named in all uppercase letters.`<ref>`{=html}

\"What is the history for naming constants in all
uppercase?\"

```{=html}
</ref>
```
[^7][^8][^9][^10]

## Further reading

There are a huge number of C style guidelines.

-   \"C and C++ Style
    Guides\" by Chris Lott
    lists many popular C style guides.
-   The Motor Industry Software Reliability Association (MISRA)
    publishes \"MISRA-C: Guidelines for the use of the C language in
    critical systems\". (Wikipedia: MISRA
    C; 1).

pl:C/Powszechne praktyki

[^1]: comp.lang.c FAQ list: \"Why isn\'t a pointer null after calling
    free?\" mentions that
    \"it is often useful to set \[pointer variables\] to NULL
    immediately after freeing them\".

[^2]: \"The C Preprocessor: Swallowing the
    Semicolon\"

[^3]: \"Why use apparently meaningless do-while and if-else statements
    in
    macros?\"

[^4]: \"do {\...} while (0) in
    macros\"

[^5]: \"KernelNewbies: FAQ /
    DoWhile0\".

[^6]: \"PRE10-C. Wrap multistatement macros in a do-while
    loop\".

[^7]: \"The
    Preprocessor\".

[^8]: \"C Language Style
    Guide\".

[^9]: \"non capitalized macros are always
    evil\".

[^10]: \"Exploiting the Preprocessor for Fun and
    Profit\".


# C Programming/Preprocessor directives and macros

Preprocessors are a way of making text processing with your C program
before they are actually compiled. Before the actual compilation of
every C program it is passed through a Preprocessor. The Preprocessor
looks through the program trying to find out specific instructions
called Preprocessor directives that it can understand. All Preprocessor
directives begin with the \# (hash) symbol. C++ compilers use the same C
preprocessor.[^1]

The preprocessor is a part of the compiler
which performs preliminary operations (conditionally compiling code,
including files etc\...) to your code before the compiler sees it. These
transformations are lexical, meaning that the output of the preprocessor
is still text.

  -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
  NOTE: Technically the output of the preprocessing phase for C consists of a sequence of tokens, rather than source text, but it is simple to output source text which is equivalent to the given token sequence, and that is commonly supported by compilers via a `-E` or `/E` option \-- although command line options to C compilers aren\'t completely standard, many follow similar rules.
  -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

## Directives

Directives are special instructions directed to the preprocessor
(preprocessor directive) or to the compiler
(compiler directive) on how it should process part or all of your source
code or set some flags on the final object and are used to make writing
source code easier (more portable for instance) and to make the source
code more understandable. Directives are handled by the preprocessor,
which is either a separate program invoked by the compiler or part of
the compiler itself.

### #include

C has some features as part of the language and some others as part of a
**standard library**, which is a repository of code that is available
alongside every standard-conformant C compiler. When the C compiler
compiles your program it usually also links it with the standard C
library. For example, on encountering a `#include <stdio.h>` directive,
it replaces the directive with the contents of the `stdio.h` header
file.

When you use features from the library, C requires you to *declare* what
you would be using. The first line in the program is a **preprocessing
directive** which should look like this:

`#include <stdio.h>`

The above line causes the C declarations which are in the `stdio.h`
header to be included for use in your
program. Usually this is implemented by just inserting into your program
the contents of a **header file** called `stdio.h`, located in a
system-dependent location. The location of such files may be described
in your compiler\'s documentation. A list of standard C header files is
listed below in the Headers table.

The `stdio.h` header contains various declarations for input/output
(I/O) using an abstraction of I/O mechanisms called **streams**. For
example there is an output stream object called `stdout` which is used
to output text to the standard output, which usually displays the text
on the computer screen.

If using angle brackets like the example above, the preprocessor is
instructed to search for the include file along the development
environment path for the standard includes.

`#include "other.h"`

If you use quotation marks (`" "`), the preprocessor is expected to
search in some additional, usually user-defined, locations for the
header file, and to fall back to the standard include paths only if it
is not found in those additional locations. It is common for this form
to include searching in the same directory as the file containing the
`#include` directive.

  ------------------------------------------------------------------------------------------------------------------------------------------------------------
  NOTE: You should check the documentation of the development environment you are using for any vendor specific implementations of the `#include` directive.
  ------------------------------------------------------------------------------------------------------------------------------------------------------------

#### Headers

`<b>`{=html}The C90 standard headers list:`</b>`{=html}

```{=html}
<table>
```
```{=html}
<td>
```
-   `<assert.h>`
-   `<ctype.h>`
-   `<errno.h>`
-   `<float.h>`
-   `<limits.h>`

```{=html}
</td>
```
```{=html}
<td>
```
-   `<locale.h>`
-   `<math.h>`
-   `<setjmp.h>`
-   `<signal.h>`
-   `<stdarg.h>`

```{=html}
</td>
```
```{=html}
<td>
```
-   `<stddef.h>`
-   `<stdio.h>`
-   `<stdlib.h>`
-   `<string.h>`
-   `<time.h>`

```{=html}
</td>
```
```{=html}
</table>
```
`<b>`{=html}Headers added since C90:`</b>`{=html}

```{=html}
<table>
```
```{=html}
<td>
```
-   `<complex.h>`
-   `<fenv.h>`
-   `<inttypes.h>`

```{=html}
</td>
```
```{=html}
<td>
```
-   `<iso646.h>`
-   `<stdbool.h>`
-   `<stdint.h>`

```{=html}
</td>
```
```{=html}
<td>
```
-   `<tgmath.h>`
-   `<wchar.h>`
-   `<wctype.h>`

```{=html}
</td>
```
```{=html}
</table>
```
### #pragma

The **pragma** (pragmatic information) directive is part of the
standard, but the meaning of any pragma depends on the software
implementation of the standard that is used. The #pragma directive
provides a way to request special behavior from the compiler. This
directive is most useful for programs that are unusually large or that
need to take advantage of the capabilities of a particular compiler.

Pragmas are used within the source program.

`#pragma token(s)`

1.  pragma is usually followed by a single token, which represents a
    command for the compiler to obey. You should check the software
    implementation of the C standard you intend on using for a list of
    the supported tokens. Not surprisingly, the set of commands that can
    appear in #pragma directives is different for each compiler; you\'ll
    have to consult the documentation for your compiler to see which
    commands it allows and what those commands do.

For instance one of the most implemented preprocessor directives,
`#pragma once` when placed at the beginning of a header file, indicates
that the file where it resides will be skipped if included several times
by the preprocessor.

  ----------------------------------------------------------------------------------------------------
  NOTE: Other methods exist to do this action that is commonly referred as using **include guards**.
  ----------------------------------------------------------------------------------------------------

\
\

### `#define`

Each `#define` preprocessor instruction defines a macro. For example,

`   #define PI 3.14159265358979323846 /* pi */`

A macro defined with a space immediately after the name is called a
constant or literal. A macro defined with a parenthesis immediately
after the name is called a function-like macro.[^2]

+----------------------------------------------------------------------+
| WARNING: Preprocessor macros, although tempting, can produce quite   |
| unexpected results if not done right. Always keep in mind that       |
| macros are textual substitutions done to your source code before     |
| anything is compiled. The compiler does not know anything about the  |
| macros and never gets to see them. This can produce obscure errors,  |
| amongst other negative effects. Prefer to use language features, if  |
| there are equivalent. For example, use `const int` or `enum` instead |
| of `#define`d constants).                                            |
|                                                                      |
| That said, there are cases, where macros are very useful (see the    |
| `debug` macro below for an example).                                 |
+----------------------------------------------------------------------+

The `#define` directive is used to define macros. Macros are used by the
preprocessor to manipulate the program source code before it is
compiled. Because preprocessor macro definitions are substituted before
the compiler acts on the source code, any errors that are introduced by
`#define` are difficult to trace.

By convention, macros defined using `#define` are named in uppercase.
Although doing so is not a requirement, it is considered very bad
practice to do otherwise. This allows the macros to be easily identified
when reading the source code. (We mention many other common conventions
for using `#define` in a later chapter, C Programming/Common
practices).

Today, `#define` is primarily used to handle compiler and platform
differences. E.g., a define might hold a constant which is the
appropriate error code for a system call. The use of `#define` should
thus be limited unless absolutely necessary; `typedef` statements and
constant variables can often perform the same functions more safely.

Another feature of the `#define` command is that it can take arguments,
making it rather useful as a pseudo-function creator. Consider the
following code:

`#define ABSOLUTE_VALUE( x ) ( ((x) < 0) ? -(x) : (x) )`\
`...`\
`int x = -1;`\
`while( ABSOLUTE_VALUE( x ) ) {`\
`...`\
`}`\
`       `

It\'s generally a good idea to use extra parentheses when using complex
macros. Notice that in the above example, the variable \"x\" is always
within its own set of parentheses. This way, it will be evaluated in
whole, before being compared to 0 or multiplied by -1. Also, the entire
macro is surrounded by parentheses, to prevent it from being
contaminated by other code. If you\'re not careful, you run the risk of
having the compiler misinterpret your code.

Because of side-effects it is considered a very bad idea to use macro
functions as described above.

`int x = -10;`\
`int y = ABSOLUTE_VALUE( x++ );`

If ABSOLUTE_VALUE() were a real function \'x\' would now have the value
of \'-9\', but because it was an argument in a macro it was expanded
twice and thus has a value of -8.

+----------------------------------------------------------------------+
| Example:                                                             |
|                                                                      |
| To illustrate the dangers of macros, consider this naive macro       |
|                                                                      |
| `#define MAX(a,b) a>b?a:b`                                           |
|                                                                      |
| and the code                                                         |
|                                                                      |
| `i = MAX(2,3)+5;`\                                                   |
| `j = MAX(3,2)+5;`                                                    |
|                                                                      |
| Take a look at this and consider what the value after execution      |
| might be. The statements are turned into                             |
|                                                                      |
| `int i = 2>3?2:3+5;`\                                                |
| `int j = 3>2?3:2+5;`                                                 |
|                                                                      |
| Thus, after execution `i=8` and `j=3` instead of the expected result |
| of `i=j=8`! This is why you were cautioned to use an extra set of    |
| parenthesis above, but even with these, the road is fraught with     |
| dangers. The alert reader might quickly realize that if `a` or `b`   |
| contains expressions, the definition must parenthesize every use of  |
| `a,b` in the macro definition, like this:                            |
|                                                                      |
| `#define MAX(a,b) ((a)>(b)?(a):(b))`                                 |
|                                                                      |
| This works, provided `a,b` have no side effects. Indeed,             |
|                                                                      |
| `i = 2;`\                                                            |
| `j = 3;`\                                                            |
| `k = MAX(i++, j++);`                                                 |
|                                                                      |
| would result in `k=4`, `i=3` and `j=5`. This would be highly         |
| surprising to anyone expecting `MAX()` to behave like a function.    |
|                                                                      |
| So what is the correct solution? The solution is not to use macro at |
| all. A global, inline function, like this                            |
|                                                                      |
| `inline int max(int a, int b) { `\                                   |
| `  return a>b?a:b `\                                                 |
| `}`                                                                  |
|                                                                      |
| has none of the pitfalls above, but will not work with all types.    |
|                                                                      |
| +----------------------------------------------------------------+   |
| | NOTE: The explicit `inline` declaration is not really          |   |
| | necessary unless the definition is in a header file, since     |   |
| | your compiler can inline functions for you (with gcc this can  |   |
| | be done with `-finline-functions` or `-O3`). The compiler is   |   |
| | often better than the programmer at predicting which functions |   |
| | are worth inlining. Also, function calls are not really        |   |
| | expensive (they used to be).                                   |   |
| |                                                                |   |
| | The compiler is actually free to ignore the `inline` keyword.  |   |
| | It is only a hint (except that `inline` is necessary in order  |   |
| | to allow a function to be defined in a header file without     |   |
| | generating an error message due to the function being defined  |   |
| | in more than one translation unit).                            |   |
| +----------------------------------------------------------------+   |
+----------------------------------------------------------------------+

(**#, \##**)

The **\#** and **\##** operators are used with the `#define` macro.
Using \# causes the first argument after the **\#** to be returned as a
string in quotes. For example, the command

`#define as_string( s ) # s`\
`       `

will make the compiler turn this command

`puts( as_string( Hello World! ) ) ;`\
`       `

into

`puts( "Hello World!" );`\
`       `

Using **\##** concatenates what\'s before the **\##** with what\'s after
it. For example, the command

`#define concatenate( x, y ) x ## y`\
`...`\
`int xy = 10;`\
`...`\
`   `

will make the compiler turn

`printf( "%d", concatenate( x, y ));`\
`       `

into

`printf( "%d", xy);`\
`       `

which will, of course, display `10` to standard output.

It is possible to concatenate a macro argument with a constant prefix or
suffix to obtain a valid identifier as in

`#define make_function( name ) int my_ ## name (int foo) {}`\
`make_function( bar )`

which will define a function called `my_bar()`. But it isn\'t possible
to integrate a macro argument into a constant string using the
concatenation operator. In order to obtain such an effect, one can use
the ANSI C property that two or more consecutive string constants are
considered equivalent to a single string constant when encountered.
Using this property, one can write

`#define eat( what ) puts( "I'm eating " #what " today." )`\
`eat( fruit )`

which the macro-processor will turn into

`puts( "I'm eating " "fruit" " today." )`

which in turn will be interpreted by the C parser as a single string
constant.

The following trick can be used to turn a numeric constants into string
literals

`#define num2str(x) str(x)`\
`#define str(x) #x`\
`#define CONST 23`\
\
`puts(num2str(CONST));`

This is a bit tricky, since it is expanded in 2 steps. First
`num2str(CONST)` is replaced with `str(23)`, which in turn is replaced
with `"23"`. This can be useful in the following example:

`#ifdef DEBUG`\
`#define debug(msg) fputs(__FILE__ ":" num2str(__LINE__) " - " msg, stderr)`\
`#else`\
`#define debug(msg)`\
`#endif`

This will give you a nice debug message including the file and the line
where the message was issued. If DEBUG is not defined however the
debugging message will completely vanish from your code. Be careful not
to use this sort of construct with anything that has side effects, since
this can lead to bugs, that appear and disappear depending on the
compilation parameters.

### macros

Macros aren\'t type-checked and so they do not evaluate arguments. Also,
they do not obey scope properly, but simply take the string passed to
them and replace each occurrence of the macro argument in the text of
the macro with the actual string for that parameter (the code is
literally copied into the location it was called from).

An example on how to use a macro:

     #include <stdio.h>

     #define SLICES 8
     #define ADD(x) ( (x) / SLICES )

     int main(void)
     {
       int a = 0, b = 10, c = 6;

       a = ADD(b + c);
       printf("%d\n", a);
       return 0;
     }

\-- the result of \"a\" should be \"2\" (b + c = 16 -\> passed to ADD
-\> 16 / SLICES -\> result is \"2\")

+----------------------------------------------------------------------+
| NOTE:\                                                               |
| It is usually bad practice to define macros in headers.              |
|                                                                      |
| A macro should be defined only when it is not possible to achieve    |
| the same result with a function or some other mechanism. Some        |
| compilers are able to optimize code to where calls to small          |
| functions are replaced with inline code, negating any possible speed |
| advantage. Using typedefs, enums, and `inline` (in C99) is often a   |
| better option.                                                       |
+----------------------------------------------------------------------+

One of the few situations where inline functions won\'t work \-- so you
are pretty much forced to use function-like macros instead \-- is to
initialize compile time constants (static initialization of structs).
This happens when the arguments to the macro are literals that the
compiler can optimize to another literal. [^3]

### #error

The **#error** directive halts compilation. When one is encountered the
standard specifies that the compiler should emit a diagnostic containing
the remaining tokens in the directive. This is mostly used for debugging
purposes.

Programmers use \"#error\" inside a conditional block, to immediately
halt the compiler when the \"#if\" or \"#ifdef\" \-- at the beginning of
the block \-- detects a compile-time problem. Normally the compiler
skips the block (and the \"#error\" directive inside it) and the
compilation proceeds.

``` c
  #error message
```

### #warning

Many compilers support a **#warning** directive. When one is
encountered, the compiler emits a diagnostic containing the remaining
tokens in the directive.

``` c
  #warning message
```

### #undef

The **#undef** directive undefines a macro. The identifier need not have
been previously defined.

### #if,#else,#elif,#endif (conditionals)

The **#if** command checks whether a controlling conditional expression
evaluates to zero or nonzero, and excludes or includes a block of code
respectively. For example:

``` c
 #if 1
    /* This block will be included */
 #endif
 #if 0
    /* This block will not be included */
 #endif
```

The conditional expression could contain any C operator except for the
assignment operators, the increment and decrement operators, the
address-of operator, and the sizeof operator.

One unique operator used in preprocessing and nowhere else is the
**defined** operator. It returns 1 if the macro name, optionally
enclosed in parentheses, is currently defined; 0 if not.

The **#endif** command ends a block started by `#if`, `#ifdef`, or
`#ifndef`.

The **#elif** command is similar to `#if`, except that it is used to
extract one from a series of blocks of code. E.g.:

     #if /* some expression */
       :
       :
       :
     #elif /* another expression */
       :
     /* imagine many more #elifs here ... */
       :
     #else
     /* The optional #else block is selected if none of the previous #if or
        #elif blocks are selected */
       :
       :
     #endif /* The end of the #if block */

### #ifdef,#ifndef

The **#ifdef** command is similar to `#if`, except that the code block
following it is selected if a macro name is defined. In this respect,

`#ifdef NAME`

is equivalent to

`#if defined NAME`

The **#ifndef** command is similar to **#ifdef**, except that the test
is reversed:

`#ifndef NAME`

is equivalent to

`#if !defined NAME`

### #line

This preprocessor directive is used to set the file name and the line
number of the line following the directive to new values. This is used
to set the \_\_FILE\_\_ and \_\_LINE\_\_ macros.

## Useful Preprocessor Macros for Debugging

ANSI C defines some useful preprocessor macros and variables,[^4][^5]
also called \"magic constants\", include:

\_\_FILE\_\_ =\> The name of the current file, as a string literal\
\_\_LINE\_\_ =\> Current line of the source file, as a numeric literal\
\_\_DATE\_\_ =\> Current system date, as a string\
\_\_TIME\_\_ =\> Current system time, as a string\
\_\_TIMESTAMP\_\_ =\> Date and time (non-standard)\
\_\_cplusplus =\> undefined when your C code is being compiled by a C
compiler; 199711L when your C code is being compiled by a C++ compiler
compliant with 1998 C++ standard.\
\_\_func\_\_ =\> Current function name of the source file, as a string
(part of C99)\
\_\_PRETTY_FUNCTION\_\_ =\> \"decorated\" Current function name of the
source file, as a string (in GCC; non-standard)\

#### Compile-time assertions

Compile-time assertions can help you debug faster than using only
run-time assert() statements, because the compile-time assertions are
all tested at compile time, while it is possible that a test run of a
program may fail to exercise some run-time assert() statements.

Prior to the C11 standard, some people[^6][^7][^8] defined a
preprocessor macro to allow compile-time assertions, something like:

``` c
#define COMPILE_TIME_ASSERT(pred) switch(0){case 0:case pred:;}

COMPILE_TIME_ASSERT( BOOLEAN CONDITION );
```

The `static_assert.hpp`  Boost
library defines a similar
macro.[^9]

Since C11, such macros are obsolete, as `_Static_assert` and its macro
equivalent `static_assert` are standardized and built-in to the
language.

#### X-Macros

One little-known usage pattern of the C preprocessor is known as
\"X-Macros\".[^10][^11][^12][^13] An X-Macro is a header
file
or macro. Commonly these use the extension \".def\" instead of the
traditional \".h\". This file contains a list of similar macro calls,
which can be referred to as \"component macros\". The include file is
then referenced repeatedly in the following pattern. Here, the include
file is \"xmacro.def\" and it contains a list of component macros of the
style \"foo(x, y, z)\".

``` c
#define foo(x, y, z) doSomethingWith(x, y, z);
#include "xmacro.def"
#undef foo

#define foo(x, y, z) doSomethingElseWith(x, y, z);
#include "xmacro.def"
#undef foo

(etc...)
```

The most common usage of X-Macros is to establish a list of C objects
and then automatically generate code for each of them. Some
implementations also perform any `#undef`s they need inside the X-Macro,
as opposed to expecting the caller to undefine them.

Common sets of objects are a set of global configuration settings, a set
of members of a struct "wikilink"), a
list of possible XML tags for converting an XML file
to a quickly-traversable tree, or the body of an
enum declaration; other lists are
possible.

Once the X-Macro has been processed to create the list of objects, the
component macros can be redefined to generate, for instance, accessor
and/or mutator functions. Structure
serializing and deserializing are also
commonly done.

Here is an example of an X-Macro that establishes a struct and
automatically creates serialize/deserialize functions. For simplicity,
this example doesn\'t account for endianness or buffer overflows.

File **star.def**:

``` c
EXPAND_EXPAND_STAR_MEMBER(x, int)
EXPAND_EXPAND_STAR_MEMBER(y, int)
EXPAND_EXPAND_STAR_MEMBER(z, int)
EXPAND_EXPAND_STAR_MEMBER(radius, double)
#undef EXPAND_EXPAND_STAR_MEMBER
```

File **star_table.c**:

``` c
typedef struct {
  #define EXPAND_EXPAND_STAR_MEMBER(member, type) type member;
  #include "star.def"
  } starStruct;

void serialize_star(const starStruct *const star, unsigned char *buffer) {
  #define EXPAND_EXPAND_STAR_MEMBER(member, type) \
    memcpy(buffer, &(star->member), sizeof(star->member)); \
    buffer += sizeof(star->member);
  #include "star.def"
  }

void deserialize_star(starStruct *const star, const unsigned char *buffer) {
  #define EXPAND_EXPAND_STAR_MEMBER(member, type) \
    memcpy(&(star->member), buffer, sizeof(star->member)); \
    buffer += sizeof(star->member);
  #include "star.def"
  }
```

Handlers for individual data types may be created and accessed using
token concatenation (\"`##`\") and quoting (\"`#`\") operators. For
example, the following might be added to the above code:

``` c
#define print_int(val)    printf("%d", val)
#define print_double(val) printf("%g", val)

void print_star(const starStruct *const star) {
  /* print_##type will be replaced with print_int or print_double */
  #define EXPAND_EXPAND_STAR_MEMBER(member, type) \
    printf("%s: ", #member); \
    print_##type(star->member); \
    printf("\n");
  #include "star.def"
  }
```

Note that in this example you can also avoid the creation of separate
handler functions for each datatype in this example by defining the
print format for each supported type, with the additional benefit of
reducing the expansion code produced by this header file:

``` c
#define FORMAT_(type) FORMAT_##type
#define FORMAT_int    "%d"
#define FORMAT_double "%g"

void print_star(const starStruct *const star) {
  /* FORMAT_(type) will be replaced with FORMAT_int or FORMAT_double */
  #define EXPAND_EXPAND_STAR_MEMBER(member, type) \
    printf("%s: " FORMAT_(type) "\n", #member, star->member);
  #include "star.def"
  }
```

The creation of a separate header file can be avoided by creating a
single macro containing what would be the contents of the file. For
instance, the above file \"star.def\" could be replaced with this macro
at the beginning of:

File **star_table.c**:

``` c
#define EXPAND_STAR \
  EXPAND_STAR_MEMBER(x, int) \
  EXPAND_STAR_MEMBER(y, int) \
  EXPAND_STAR_MEMBER(z, int) \
  EXPAND_STAR_MEMBER(radius, double)
```

and then all calls to `#include "star.def"` could be replaced with a
simple `EXPAND_STAR` statement. The rest of the above file would become:

``` c
typedef struct {
  #define EXPAND_STAR_MEMBER(member, type) type member;
  EXPAND_STAR
  #undef  EXPAND_STAR_MEMBER
  } starStruct;

void serialize_star(const starStruct *const star, unsigned char *buffer) {
  #define EXPAND_STAR_MEMBER(member, type) \
    memcpy(buffer, &(star->member), sizeof(star->member)); \
    buffer += sizeof(star->member);
  EXPAND_STAR
  #undef  EXPAND_STAR_MEMBER
  }

void deserialize_star(starStruct *const star, const unsigned char *buffer) {
  #define EXPAND_STAR_MEMBER(member, type) \
    memcpy(&(star->member), buffer, sizeof(star->member)); \
    buffer += sizeof(star->member);
  EXPAND_STAR
  #undef  EXPAND_STAR_MEMBER
  }
```

and the print handler could be added as well as:

``` c
#define print_int(val)    printf("%d", val)
#define print_double(val) printf("%g", val)

void print_star(const starStruct *const star) {
  /* print_##type will be replaced with print_int or print_double */
  #define EXPAND_STAR_MEMBER(member, type) \
    printf("%s: ", #member); \
    print_##type(star->member); \
    printf("\n");
  EXPAND_STAR
  #undef EXPAND_STAR_MEMBER
}
```

or as:

``` c
#define FORMAT_(type) FORMAT_##type
#define FORMAT_int    "%d"
#define FORMAT_double "%g"

void print_star(const starStruct *const star) {
  /* FORMAT_(type) will be replaced with FORMAT_int or FORMAT_double */
  #define EXPAND_STAR_MEMBER(member, type) \
    printf("%s: " FORMAT_(type) "\n", #member, star->member);
  EXPAND_STAR
  #undef EXPAND_STAR_MEMBER
  }
```

A variant which avoids needing to know the members of any expanded
sub-macros is to accept the operators as an argument to the list macro:

File **star_table.c**:

``` c
/*
 Generic
 */
#define STRUCT_MEMBER(member, type, dummy) type member;

#define SERIALIZE_MEMBER(member, type, obj, buffer) \
  memcpy(buffer, &(obj->member), sizeof(obj->member)); \
  buffer += sizeof(obj->member);

#define DESERIALIZE_MEMBER(member, type, obj, buffer) \
  memcpy(&(obj->member), buffer, sizeof(obj->member)); \
  buffer += sizeof(obj->member);

#define FORMAT_(type) FORMAT_##type
#define FORMAT_int    "%d"
#define FORMAT_double "%g"

/* FORMAT_(type) will be replaced with FORMAT_int or FORMAT_double */
#define PRINT_MEMBER(member, type, obj) \
  printf("%s: " FORMAT_(type) "\n", #member, obj->member);

/*
 starStruct
 */

#define EXPAND_STAR(_, ...) \
  _(x, int, __VA_ARGS__) \
  _(y, int, __VA_ARGS__) \
  _(z, int, __VA_ARGS__) \
  _(radius, double, __VA_ARGS__)

typedef struct {
  EXPAND_STAR(STRUCT_MEMBER, )
  } starStruct;

void serialize_star(const starStruct *const star, unsigned char *buffer) {
  EXPAND_STAR(SERIALIZE_MEMBER, star, buffer)
  }

void deserialize_star(starStruct *const star, const unsigned char *buffer) {
  EXPAND_STAR(DESERIALIZE_MEMBER, star, buffer)
  }

void print_star(const starStruct *const star) {
  EXPAND_STAR(PRINT_MEMBER, star)
  }
```

This approach can be dangerous in that the entire macro set is always
interpreted as if it was on a single source line, which could encounter
compiler limits with complex component macros and/or long member lists.

This technique was reported by Lars Wirzenius[^14] in a web page dated
January 17, 2000, in which he gives credit to Kenneth Oksanen for
\"refining and developing\" the technique prior to 1997. The other
references describe it as a method from at least a decade before the
turn of the century.

We discuss X-Macros more in a later section, Serialization and
X-Macros.

de:C-Programmierung:
Präprozessor
fr:Programmation
C/Préprocesseur
it:C/Compilatore e
precompilatore/Direttive
pl:C/Preprocesor

[^1]: Understanding C++/C
    Preprocessor

[^2]: \"Exploiting the Preprocessor for Fun and
    Profit\".

[^3]: David Hart, Jon Reid. \"9 Code Smells of Preprocessor
    Use\". 2012.

[^4]: HP C Compiler Reference
    Manual

[^5]: C++ reference: Predefined preprocessor
    variables

[^6]: \"Compile Time Assertions in
    C\" by Jon Jagger 1999

[^7]: Pádraig Brady. \"static
    assertion\".

[^8]: \"ternary operator with a constant (true)
    value?\".

[^9]: Wikipedia: C++0x#Static
    assertions

[^10]: Wirzenius, Lars. C Preprocessor Trick For Implementing Similar
    Data Types Retrieved
    January 9, 2011.

[^11]:

[^12]:

[^13]: Keith Schwarz. \"Advanced Preprocessor
    Techniques\".
    2009. Includes \"Practical Applications of the Preprocessor II: The
    X Macro Trick\".

[^14]: Wirzenius, Lars. C Preprocessor Trick For Implementing Similar
    Data Types Retrieved
    January 9, 2011.


# C Programming/Serialization

## Serialization

It is often necessary to send or receive complex data structures to or
from another program that may run on a different architecture or may
have been designed for different version of the data structures in
question. A typical example is a program that saves its state to a file
on exit and then reads it back when started.

The \'send\' function will typically start by writing a magic identifier
and version to the file or network socket and then proceed to write all
the data members one by one (i.e. in serial). If variable length arrays
are encountered (e.g. strings), it will either write a length followed
by the data or it will write the data followed by a special terminator.
The format is often XML or binary; in the latter case the htonl() set of
macros may come in handy.

The \'receive\' function will be nearly identical: it will read all the
items one by one. Variable length arrays are either handled by reading
the count followed by the data, or by reading the data until the special
terminator is reached.

Since these two functions often follow the same pattern as the
declaration of the data(structures), it would be nice if they could all
be generated from a common definition.

## X-Macros

X-Macros uses the preprocessor to force the compiler to compile the same
piece of text more than once. Sometimes a special file (with extension
.def) is included multiple times. For example variables.def may look
like this :

`INT(value)`\
`INT(shift)`

In this example the C programming will then look like this :

`...`\
`#define INT(var) int var;`\
`#include "variables.def"`\
`#undef INT`\
`...`\
`printf ("version=1\n");`\
`#define INT(var) printf (#var "=%d\n", var);`\
`#include "variables.def"`\
`#undef INT`\
`...`

If including a separate file multiple times is undesirable, another
macro can be used. For example :

`#define VARIABLES INT(value) \`\
`                  INT(shift)`

The `#include`s can then be replaced with calls to the macro.

Using this method, one can also pass in the name(s) of (an)other
macro(s) that can operate on the list of values. For example:

`#define VAR_LIST(_) _(value) \`\
`                    _(shift)`\
`...`\
`#define VAR_INT_DECL(var) int var;`\
`VAR_LIST(VAR_INT_DECL)`\
`...`\
`printf ("version=1\n");`\
`#define VAR_INT_PRINTF(var) printf (#var "=%d\n", var);`\
`VAR_LIST(VAR_INT_PRINTF)`\
`...`

This does not require the redefinition of macros and can make the code
easier to understand and maintain.

X-Macros are also particularly useful for keeping mappings between
strings and enumerated types synchronized.

## Serialization with versioning

Suppose we want to add additional variables to the above example, but we
still want the program to be able to read the old version 1 files. Then
we would add a version parameter and a default value parameter to the
list processing macros:

`#define VAR_LIST(_) _(value,1,0) \`\
`                    _(shift,1,0) \`\
`                    _(mask,2,0xffff)`\
`...`\
`int inputVer;`\
`#define VAR_INT_DECL(var,varVer,default) int var;`\
`VAR_LIST(VAR_INT_DECL)`\
`...`\
`scanf ("version=%d", &inputVer);`\
`#define VAR_INT_SCN(var,varVer,default) if (varVer <= inputVer) scanf (#var "=%d", &var); else var = default;`\
`VAR_LIST(VAR_INT_SCN)`\
`...`\
`printf ("version=2\n"); /* Always output at highest known version */`\
`#define VAR_INT_PRT(var,varVer,default) printf (#var "=%d\n", var);`\
`VAR_LIST(VAR_INT_PRT)`\
`...`


# C Programming/Coroutines

A little known fact is that most C implementations have built-in
primitives that can be used for cooperative multitasking / coroutines.
They are setcontext and
setjmp.

## setjmp

The function `setjmp` is used in a pair with `longjmp` to transfer
execution to a different point in the code. It relies on an existing
`jmp_buf` declaration.

``` c
#include <setjmp.h>

int main (void)
{
  jmp_buf buf1;

  if (setjmp(buf1) == 0)
  {
    /* This code is executed on the first call to setjmp. */

    longjmp(buf1, 1);
  } else {
    /* This code is executed once longjmp is called. */
  }
  return 0;
}
```

`setjmp()` stores the current execution point in memory, which remains
valid as long as the containing function doesn\'t return. It initially
returns `0`. Control is returned to `setjmp` once `longjmp` is called
with the original `jmp_buf` and the replacement return value.

Note that jmp_buf is passed to setjmp without using the address-of
operator.

The easiest way to understand setjmp and longjmp, is that setjmp stores
the state of the cpu which includes program counter, stack pointer, all
the registers, including the bits of the flags register, at the location
pointed to by jmp_buf , which is defined some LEN+1, which is enough
bytes to store the registers of whatever CPU is involved. The
longjmp(buf) , never returns, because it restores the CPU from the
contents of struct jmp_buf buf previously set by a previous call the
setjmp, so execution begins from after setjmp was called, but the return
value of setjmp is not 0, but whatever value was used in the second
parameter to longjmp. This is similar to the fork() system call, which
returns 0 to the child process, and the PID of the child process to the
parent.

The internet suggests co-routines are useful for implementing software
as state machines cooperating, such as lexer processing input text and
emitting tokens , so that a parser can decide to store the token and ask
for the next one, or to act on its current set of token . This is not
multithreaded programs synchronising on data, with possibly race
conditions if a bug forgets to acquire a lock, but with setjmp and
longjmp, seems to be cooperative processes that guarantee only one
process will run at a time, with no worries about context switches
waking up sleeping processes ( using separate jmp_buf static locations,
each process can call setjmp for its own jmp_buf, before calling longjmp
later on if zero was returned, or continue a loop to process shared data
for non-zero returns).


# C Programming/Particularities of C

C is an efficient, minimalist language that has some peculiarities that
a programmer must be aware of. To address these, sometimes a good
solution is to combine another language with C for added flexibility and
power, like the combination of Emacs-LISP and C used for Emacs.
Sometimes they can be addressed at the cost of slower speed and
increased complexity by using special constructs that will guarantee
function and security. Mostly however, through practice, C programmers
have no trouble with the things mentioned here, and prefer using a
language that closely models the general purpose, Von Neumann hardware
architecture.

Below are several of these particularities of ANSI C (that sometimes are
also its strengths), some minor and some major:

Lack of differentiation between arrays and pointers : The very first C (around 1973) did not have arrays at all; modern implementations are contiguous areas in memory accessed with pointer arithmetic (note: a declared array cannot be assigned to like a pointer), which circumvents the need to declare arrays with a fixed size. This ability, however, can cause buffer overflow errors with careless use.

```{=html}
<!-- -->
```

Arrays do not store their length : A consequence of the above feature. This means that the program might need to explicitly perform a bounds check before accessing an array. Unless a function is passed an array of a fixed size, there is no way for it to discover the length of the array it was given: So the function must be given the length, perhaps passed to the function as a separate variable or in a structure. Because of this, most implementations do not provide automatic array bounds checking, and manual bounds checking is error prone.

```{=html}
<!-- -->
```

:   If a C (or C++) program attempts to access an array element outside
    of the actual allocated memory, then a buffer overflow occurs,
    typically crashing the program. Buffer overflow bugs are a common
    security vulnerability too. Many other computer languages provide
    automatic bounds checking, and so they are nearly immune to such
    bugs. [^1][^2][^3][^4][^5]

```{=html}
<!-- -->
```

Variable Length Arrays : A VLA ‒ variable length array ‒ can only be used for function parameters and auto variables. VLAs cannot be used inside a structure (except as the last item in the structure). It\'s not possible to define a structure that corresponds to the standard Forth dictionary definition (which has 2 variable-length parts), except as an undifferentiated array of `char`.

```{=html}
<!-- -->
```

Arbitrary-size built-in 2D or 3D arrays are not widely supported : This feature has been added starting with the C99 specification for variable-length arrays, although many C compilers still do not support it. Without VLAs, there is no way for a function to accept 2D or 3D arrays of arbitrary size. In particular, it\'s impossible to define a function that accepts `int a[5][4][3];` on one call, and later accepts `int b[10][10][10];` in a later call. Instead of using the built-in 2D or 3D array data type, C programmers use some other data type to hold (mathematical) 2D or 3D arrays of arbitrary size (multi-dimensional arrays) \-- see C Programming/Common practices#Dynamic multidimensional arrays for details.

```{=html}
<!-- -->
```

No formal String data type : Strings are character arrays (lacking any abstraction) and inherit all their constraints (structs can provide an abstraction, to an extent).

```{=html}
<!-- -->
```

Weak type safety : C is not very type-safe. The memory management functions operate on untyped pointers, there is no built-in run-time type enforcement, and the type system can be circumvented with pointers and casts. Additionally, typedef does not create a new type but only an alias, thus it serves solely for code legibility. However, it is possible to use single member structs to enforce type safety.

```{=html}
<!-- -->
```

No garbage collection : As a low-level language designed for minimum overhead, C features only manual memory management, which can allow simple memory leaks to go on unchecked.

```{=html}
<!-- -->
```

Local variables are uninitialized upon declaration : Local (but not global) variables must be initialized manually; before this, they contain whatever was already in memory at the time. This is not unusual, but the C standard does not forbid access to uninitialized variables (which is).

```{=html}
<!-- -->
```

Unwieldy function pointer syntax : Function pointers take the form of `[return type] name([arg2 type])`, making them somewhat difficult to use. Typedefs can alleviate this burdensome syntax. For example, `typedef int fn(int i);`. See C Programming/Pointers and arrays#Pointers to Functions for more details.

```{=html}
<!-- -->
```

No reflection : It is not possible for a C program \-- at runtime \-- to evaluate a string as if it were a source C code statement.

```{=html}
<!-- -->
```

Nested functions are not standard: However, many C compilers do support nested functions, including GNU C.`<ref>`{=html}

\"A GNU Manual\": \"Extensions to the C Language: Nested Functions\"
1

```{=html}
</ref>
```

No formal exception handling :Some standard functions return special values that must be handled manually. For example, `malloc()` returns null upon failure. For example, one must store the return value of `getchar()` in an `int` (not, as one might expect, in a `char`) in order to reliably detect the end-of-file \-- see  EOF pitfall. Programs that do not include appropriate error handling might work fine most of the time, but can crash or otherwise malfunction when exceptional cases occur. POSIX systems often use `signal()` to handle some kinds of exceptions. (See C Programming/Error handling#Signals for details). Some programs use `setjmp()`, `longjmp()` or `goto` to manually handle some kinds of exceptions. (See C Programming/Control#One last thing: goto and C Programming/Coroutines for details).

```{=html}
<!-- -->
```

No anonymous function definitions

## References

[^1]: <http://projects.webappsec.org/Buffer-Overflow>

[^2]: <http://www.dwheeler.com/secure-programs/Secure-Programs-HOWTO/buffer-overflow.html>

[^3]: <http://searchsecurity.techtarget.com/news/article/0,289142,sid14_gci860185,00.html>

[^4]: <http://www.owasp.org/index.php/Buffer_Overflows>

[^5]: <http://cyclone.thelanguage.org/wiki/Why%20Cyclone>


# C Programming/Low-level IO

## File descriptors

While not specified by the C standard, many operating systems provide
the concept of a **file descriptor** (sometimes abbreviated as **fd**).
While the `FILE` type from `stdio.h` and its associated
functions encapsulate the low-level details of
a stream, a file descriptor is an integer that refers to a stream that
the operating system is keeping track of.

This section will explore file descriptors as they are implemented in
POSIX systems, such as Linux.

### Standard streams as file descriptors

When a process is being created, the operating system allocates, among
other resources, three streams for a process: the standard streams
`stdin`, `stdout`, and `stderr`. Typically, the standard streams are
interacted with using their `FILE`-based definitions in `stdio.h`, as
covered in an earlier section. These streams can also be interacted with
through their raw file descriptors, which are the same for each process:

  `unistd.h` symbol   stream     File descriptor
  ------------------- ---------- -----------------
  `STDIN_FILENO`      `stdin`    `0`
  `STDOUT_FILENO`     `stdout`   `1`
  `STDERR_FILENO`     `stderr`   `2`

Notice that these file descriptors are the same for every process, even
though the standard streams contain different data for each process.
This means that file descriptors are not necessarily unique system-wide;
each process may have a different view of which file descriptors map to
which streams, just like how each process has a different view of the
system\'s virtual address space.

### Basic reading and writing

Reading to and writing from a file descriptor can be performed using the
following functions:[^1]

``` c
#include <unistd.h>
ssize_t read(int fd, void *buf, size_t count);
ssize_t write(int fd, const void *buf, size_t count);
```

Compare and contrast these definitions with the `FILE`-based
functions:[^2]

``` c
#include <stdio.h>
char *fgets(char *s, int size, FILE *stream);
int fputs(const char *s, FILE *stream);
```

Three differences are apparent:

1.  The data being read from and written to the stream are not assumed
    to be strings.
2.  File descriptors are taken as parameters instead of `FILE`s.
3.  A consistent type is used for the return value.

`read` and `fgets` take similar sets of parameters: something
representing the stream, a buffer, and a size; additionally, if the
amount of data read equals the requested size, the buffer will have the
same contents regardless of the function used. However, these functions
behave differently in the case where the amount of data read does not
match the requested size. `fgets`, being intended for use with strings,
will stop reading early if a newline is encountered, and the function
may block if it is waiting for the rest of the string to appear in the
stream. `read`, on the other hand, won\'t stop reading early if a
special value is encountered, but it will stop if not all the requested
data has been written to the pipe yet. Since `read` can\'t guarantee
that something wholly usable has been written to the buffer (in the case
that it stops reading early), the return value contains the number of
bytes written to the buffer. This makes `read` more appropriate for
situations where the programmer needs more control over the type of the
data being read or is willing to trade receiving partially-read data for
reducing the number of blocking I/O operations.

Similarly, `write` needs an explicit size parameter since it can\'t
assume a NULL-terminated string is being written, and it will return the
number of bytes written so the program can determine whether the passed
data was fully written to the stream.

### Obtaining and discarding file descriptors

### `FILE`-file descriptor conversions

### Security through `openat`

[^1]: read(2) and write(2), Linux Programmer\'s Manual, 2019-10-10

[^2]: fgets(3) and fputs(3), Linux Programmer\'s Manual, 2020-08-13


# C Programming/C trigraph

## Trigraphs

C was designed in English and assumes the common English character set,
which includes such characters as `{`, `}`, `[`, `]`, and so on. Some
other languages, however, do not have these or other characters which
are required by C. To solve this problem, the 1989 C standard in section
5.2.1.1 defined a set of `<i>`{=html}trigraph sequences`</i>`{=html}
which can be substitutes for the symbols and which will work in any
situation. In fact, the first translation phase of compilation specified
in the 1989 C standard (section 5.1.1.2) is to replace the trigraph
sequences with their corresponding single-character equivalents. Note
that trigraphs will be removed from C after the next major standard of
it, C23, is released.[^1]

The following trigraph sequences exist, and no other. Each question mark
`?` that does not begin one of the trigraph sequences listed is not
changed.

`Sequence Replacement`\
`======== ===========`\
`  ??=         #`\
`  ??(         [`\
`  ??/         \`\
`  ??)         ]`\
`  ??'         ^`\
`  ??<         {`\
`  ??!         |`\
`  ??>         }`\
`  ??-         ~`

The effect of this is that statements such as

``` c
printf ("Eh???/n");
```

will, after the trigraph is replaced, be the equivalent of

``` c
printf ("Eh?\n");
```

Should the programmer want the trigraph *not* to be replaced, within
strings and character constants (which is the only place they would need
replacing and it would change things), the programmer can simply escape
the second question mark; e.g.

``` c
 printf ("Two question marks in a row: ?\?!\n");
```

The 1999 C standard added these punctuators, sometimes called
`<i>`{=html}digraphs`</i>`{=html}, in section 6.4.6. They are equivalent
to the following tokens except for their spelling:

`Digraph Equivalent`\
`======= ==========`\
`   <:       [`\
`   :>       ]`\
`   <%       {`\
`   %>       }`\
`   %:       #`\
`  %:%:      ##`

In other words, they behave differently when stringized as part of a
macro replacement, but are otherwise equivalent.

## References

[^1]: <https://www.open-std.org/jtc1/sc22/wg14/www/docs/n2940.pdf>


# C Programming/Language overloading and extensions

Most C compilers have one or more \"extensions\" to the standard C
language, to do things that are inconvenient to do in standard, portable
C.

Some examples of language extensions:

-   in-line assembly language
-   interrupt service routines
-   variable-length data structure (a structure whose last item is a
    \"zero-length array\").`<ref>`{=html}

comp.lang.c FAQ list: Question
2.6: \"C99 introduces the
concept of a flexible array member, which allows the size of an array to
be omitted if it is the last member in a structure, thus providing a
well-defined solution.\"

```{=html}
</ref>
```
-   re-sizeable multidimensional arrays
-   various \"#pragma\" settings to compile quickly, to generate fast
    code, or to generate compact code.
-   bit manipulation, especially bit-rotations and things involving the
    \"carry\" bit
-   storage alignment
-   Arrays whose length is computed at run time.

## External links

-   GNU C: Extensions to the C
    Language
-   C/C++ interpreter Ch extensions to the C language for
    scripting
-   SDCC: Storage Class Language
    Extensions

```{=html}
<references />
```


# C Programming/Mixing languages

## Assembler

See Embedded Systems/Mixed C and Assembly
Programming

## Cg

Make the main program (for CPU) in C, which loads and run the
Cg "wikilink") program ( for GPU
).[^1][^2][^3]

### Header files

Add to C program:[^4]

``` c
#include <Cg/cg.h> /* To include the core Cg runtime API into your  program */
#include <Cg/cgGL.h>  /* to include the OpenGL-specific Cg runtime API */
```

### Minimal program

-   by bobobobo[^5]

## Java

Using the Java native interface (JNI), Java applications can call C
libraries.

See also

-   Java_Programming/Keywords/native

## Perl

To mix Perl and C, we can use XS. XS is an interface description file
format used to create an extension interface between Perl and C code (or
a C library) which one wishes to use with Perl.

The basic procedure is very simple. We can create the necessary
subdirectory structure by running \"h2xs\" application (e.g. \"h2xs -A
-n Modulename\"). This will create - among others - a Makefile.PL, a .pm
Perl module and a .xs XSUB file in the subdirectory tree. We can edit
the .xs file by adding our code to that, let\'s say:

`void`\
`hello()`\
`  CODE:`\
`    printf("Hello, world!\n");`

and we can successfully use our new command at Perl side, after running
a \"perl Makefile.PL\" and \"make\".

Further details can be found on the
perlxstut
perldoc page.

## Python

Here can be found some details about extending Python with modules
written in C. You
might read about Cython and
Pyrex as
well, that makes easier to create modules in C, translating a
Python-like code into C.  Using the Python
ctypes module, one can
write C code directly into Python.

## Further reading

-   Embedded Systems/Mixed C and Assembly
    Programming

## References

```{=html}
<references/>
```
pl:C/Łączenie z innymi
językami

[^1]: Lesson: 47 from NeHe
    Productions

[^2]: Cg Bumpmapping by Razvan Surdulescu at
    GameDev

[^3]: \[<http://www.fusionindustries.com/default.asp?page=cg-hlsl-faq>
    \| Cg & HLSL Shading Language FAQ

    `by Fusion Industries]`

[^4]: <http://http.developer.nvidia.com/CgTutorial/cg_tutorial_appendix_b.html>
    NVidia Cg tutorial. Appendix B. The Cg Runtime

[^5]: Absolutely minimal CG program for good fundamentals
    understanding


# C Programming/GObject

Since the C Programming-Language was not created with Object Oriented
Programming in mind, it has no explicit support for classes,
inheritance, polymorphism and other OO Concepts. Neither does it have
its own Virtual Table, which is found in object-oriented languages such
C++, Java
and C#. Therefore, it might not be as
easy to implement an object-oriented programming paradigm using only
C\'s language features and standard library. However, it can be done
using structures which contain both function pointers as well as data,
for example, or by using third-party libraries.

There are many third-party libraries designed to add support for
object-oriented programming in C. The most general-purpose and widely
used among these is the GObject System, which is part of Glib. The
GObject System comes with its own virtual table. To create an object in
C using the GObject system, it has to be sub-classed from the GObject
struct.

## Object-Creation

In this example a new object will be implemented directly derived from
GObject. For simplicity, the object is named *MyObject*.

### Declaring An Object

To create a simple non-derivable (final)
_object_, two structs must be declared, the
*instance* and the *class*. They are declared using a macro:

``` c
/* in myobject.h */
G_DECLARE_FINAL_TYPE (MyObject, my_object, MY, OBJECT, GObject)
```

This declares two structures, MyObject and MyObjectClass. MyObject must
be defined in the C implementation, and MyObjectClass is already defined
by the macro.

### Boiler-Plate Code

Since the GObject System is just a third-party library and therefore
cannot make any changes to the C Language itself, creating a new object
requires a lot of boiler-plate code. This is mostly handled by the macro
shown above. However, the following is also required:

``` c
/* in myobject.h */
#define MY_TYPE_OBJECT my_object_get_type ()
```

The macro defines several functions, namely MY_OBJECT () and
MY_OBJECT_CLASS (), used for casting, MY_IS_OBJECT () and
MY_IS_OBJECT_CLASS () for testing whether an object or class is of the
correct type and MY_OBJECT_GET_CLASS () for getting the class structure
from an instance.

### Defining The Object

Before use, the newly created object must be
_defined_, along with the instance structure.

``` c

/* in myobject.c */

struct _MyObject
{
    GObject parent_instance;

    /* other members */
};

G_DEFINE_TYPE (MyObject, my_object, G_TYPE_OBJECT)
```

### Static Functions

There are a few _static_ functions that may or
may not to be defined, depending on your object. For a minimal object
these ones are compulsory:

``` c

/* in myobject.c */
static void
my_object_class_init (MyObjectClass *klass)
{
     /* code */
}

static void
my_object_init (MyObject *self)
{
     /* code */
}
```

### The Constructor

There is no internal way of _allocating memory_
for an object in C. Therefore an _explicit_
constructor must be declared for the new object.

``` c

/* in myobject.c */

GObject *
my_object_new (void)
{
     return g_object_new (MY_TYPE_OBJECT,
                          0);
}
```

### Object-Usage

Although creating the object using its own pointer-type is perfectly
valid, it is recommended to use the pointer-type of the object at the
top of the hierarchy i.e the furthest off base class. The newly created
object may now be used like this:

``` c

/* in main.c */

/* Note: GObject is at the top of the hierarchy. */

/* declaration and construction */
GObject *myobj = my_object_new ();

/* destruction */
g_object_unref (myobj);
```

## Inheritance

### Concept

Inheritance is one of the most widely used and useful OO Concepts. It
provides an efficient way to reuse existing code by wrapping it up into
an object and then sub-classing it. The new classes are known as derived
classes. Many object hieriarchies can be created using inheritance.
Inheritance is also one of the most efficient ways of abstracting code.

### Implementation

In the GObject System, inheritance can be achieved by sub-classing
_GObject_. Since C provides no keyword or
operator for inheritance, a derived object is usually made by declaring
the base instance and base class as a *member* of the derived instance
and derived class respectively. In C code:

``` c

/* derived object instance */
struct _DerivedObject
{
     /* the base instance is a member of the derived instance */
     BaseObject parent_instance;
};
```

## Further reading

-   Hanser. \"Object-oriented programming with
    ANSI-C\". 1994. Hanser
    describes another way of implementing classes, inheritance,
    instances, methods, objects, vtables, polymorphism, late binding,
    etc. in standard ANSI C.

```{=html}
<!-- -->
```
-   Gregory Naçu - C64OS.com. \"Object Orientation in 6502 (Take
    2)\". 2019. Greg
    Nacu describes another way of implementing classes, inheritance,
    instances, methods, objects, etc., using very little memory, in
    6502 Assembly language.

```{=html}
<!-- -->
```
-   Greg Kroah-Hartman. \"Everything you never wanted to know about
    kobjects, ksets, and ktypes\".
    mirror: \"Everything you never wanted to know about kobjects,
    ksets, and
    ktypes\".
    2007.


# C Programming/Code library

The following is an implementation of the Standard C99 version of
`<assert.h>`:

``` c
 /* assert.h header */
 #undef assert
 #ifdef NDEBUG
 #define assert(_Ignore) ((void)0)
 #else
 void _Assertfail(char *, char *, int, char *);
 #define assert(_Test) ((_Test)?((void)0):_Assertfail(#_Test,__FILE__,__LINE__,__func__))
 #endif
 /* END OF FILE */
```

``` c
 /* xassertfail.c -- _Assertfail function */
 #include <stdlib.h>
 #include <stdio.h>
 #include <assert.h>
 void
 _Assertfail(char *test, char *filename, int line_number, char *function_name)
 {
    fprintf(stderr, "Assertion failed: %s, function %s, file %s, line %d.",
            test, function_name, filename, line_number);
    abort();
 }
 /* END OF FILE */
```