# C Programming/Intro exercise

## The \"Hello, World!\" Program

Tradition dictates that we begin with a program that displays a \"Hello,
World!\" greeting to the screen, followed by a new line, and then exits.
Below is the C source code that does just that. Type this code into your
preferred text editor/IDE and save it to a file named **hello.c**.

:

``` {.c .numberLines}
#include <stdio.h>

int main(void)
{
    printf("Hello, World!\n");
    return 0;
}
```

### Source code analysis

Although this is a very simple program, a lot of hidden meaning is
packed into the many symbols you see in the code. Though your compiler
understands it, you can only guess at what the code, sprinkled with some
familiar English words, might do. One of your first jobs as a new
programmer will be to learn the many \"words\" and symbols of the C
programming language, the language your compiler understands. Once you
learn the meaning underlying the code, you will be able to \"talk to\"
the compiler and give it your own orders and build any kind of program
you are inventive and resourceful enough to create.

But note that knowing the meanings of arcane symbols is not all there is
to programming. You can\'t master another language by reading a
translation dictionary. To become fluent in another language, you have
to practice conversing in that language. Learning a programming language
is no different. You have to practice \"talking\" to the compiler with
the source code you write. So be sure to type in the code example above
and feel free to experiment and alter it with your curiosity as your
guide.

OK, so let\'s dive in and look at the first line in our program:

:

``` {.c .numberLines startFrom="1"}
#include <stdio.h>
```

Before understanding what this line does, you have to know that your
machine already comes pre-installed with some C software code. The code
is there to save you from the drudgery of writing code that performs
basic, common tasks. This reusable code is referred to as a **library.**
And so our first line in our example program signals to the compiler
that we\'d like to \"check out\" some code from the library and make use
of it in our program. Here, we are borrowing code that will help us
print text to the screen.

The way we tell the C compiler to include library code into our own code
is by using what\'s called a .
One of the very first tasks your compiler will perform is to search
through your source code for preprocessor directives which modify your
source code in some way. In our case, the `#include` preprocessor
directive tells the compiler to copy source code from a library and
insert it directly into the code where the preprocessor directive is
found. Since our directive is at the very top of the file, the library
code will be inserted at the top of the source file. (Note that this all
happens in the computer\'s memory, so the original file on your disk
never actually gets altered.)

But which library code should the compiler insert? The next bit in the
line, the `<stdio.h>`, tells the compiler to copy and paste the C code
from the **stdio.h** file into your code. The angle brackets surrounding
the file name tell the compiler to look for the file in the standard
library as opposed, to say, your own personal library of reusable code.
Note that files with the **.h** extension are called **header files**.
The stdio.h header file contains many **functions** related to input and
output that are defined according to the C standard. Though this header
file gives us access to many different functions, the only library
function we are interested in from stdio.h is the `printf` function.

OK, but what, exactly, is a function? Let\'s take a look at the next
line in our code so we can begin to get an idea:

:

``` {.c .numberLines startFrom="3"}
int main(void)
```

Here we create a **function** named `main` that is the starting point
for all C programs. All C programs require a function called \"main\" or
they will not compile. Our function name is surrounded by two mysterious
symbols, **int** and **(void)**. The \"int\" bit tells the compiler what
kind of value our function will return while the \"(void)\" bit tells
our compiler what kind of values we will \"pass\" into our function.
We\'ll skip over what exactly this means for now as these values will be
covered in more detail later in the book. The most important thing to
understand right now is that together, these symbols **declare** our
function to the compiler and tell it that it exists.

So what is a function? In computer science, the term "function" is used
a bit more loosely than in mathematics, since functions often express
imperative ideas (as in the case of C) - that is, *how-to* process,
instead of declarations. For now, suffice it to say, functions define a
set of computer statements that work together to carry out a specific
task. In C, the statements associated with a function are placed between
a set of curly braces, `{ }`, which mark the beginning and end of the
statements. Together, the curly braces and the statements are called a
**block.** Let\'s take a look at the first line in our function\'s
block:

:

``` {.c .numberLines startFrom="5"}
    printf("Hello World!\n");
```

This line of code is the heart of our program, the one that outputs our
greeting to the user's **console** (also known as the *terminal* in the
context of Unix-like operating systems), the text-based interface
installed on your computer. This statement is a **function call** and
has two main parts: the name of the library function used to print our
greeting, **printf**, followed by the data that we will pass to the
function, seen here between the pair of parentheses. The data we are
passing to the function is the **string**, "Hello World!\\n". The
\"\\n\" part at the end of the string is a special kind of character
called an **escape sequence.** The \"\\n\" escape sequence generates the
new line at the end of our text. Strings and escape sequences will be
covered in more detail later. We terminate the function call statement
with a semicolon so the compiler knows that it should begin looking for
a new statement which it finds on the next line:

:

``` {.c .numberLines startFrom="6"}
    return 0;
```

Here, we say that our `main` function returns an integer value using the
`return` keyword. The integer value we are returning is \"0\". But what
does this mean, exactly? In the specific context of the `main` function,
the value we return is called the **exit status**, which we report back
to the operating system to indicate whether our code ran without error.
As our programs grow in complexity, we can use other integers as codes
to indicate various types of errors. This style of providing exit status
is a long standing convention[^1]. We will go into much more detail on
return values of functions later in the book.

So that\'s a lot to take in, even for such a short program. Don\'t worry
if you don\'t understand all of it and don\'t worry about memorizing it.
You do not learn programming by memorizing, you learn by repetition and
by doing. Memorizing all the notes to Beethoven\'s 5th symphony does not
make you a concert pianist, you must get on the keyboard and practice
and play!

Next we will show you how to take the source code you typed in and turn
it into an executable file with your compiler.

### Compiling

Compiling is the process we used to describe translating the orders you
gave to the compiler in your source code into the machine language that
can be run by your operating system and microprocessor. In this way,
your C compiler is a middle-man. You talk to the compiler in a language
it understands, C source code, and the compiler translates the source
into machine code to save you a lot of painstaking, tedious work writing
assembly code.

If the compiler finds your source code confusing, it will throw an error
along with a message to help you fix up your source code and clear up
any confusion. You will then need to try to recompile the code and
repeat the process until it compiles without error. Note that code that
compiles without error doesn\'t mean it\'s free of bugs. It just means
the compiler understands the instructions provided by your source code.

#### Unix-like

If you are using a Unix(-like) system, such as
GNU/Linux, Mac OS X,
or Solaris, it will
probably have GCC installed, otherwise on Linux you can install it using
the package manager of your distribution. Open the virtual console or a
terminal emulator and enter the following (be certain your current
working directory is the one containing your source code):

`gcc hello.c`

By default gcc will generate our executable binary with the name
*a.out*. To run your new generated program type:

`./a.out`

You should see `Hello, World!` printed after the last prompt.

To see the exit status of the last program you ran, type on your shell
command:

`echo $?`

This shows the value the `main` function has returned, which is 0 in the
above example.

There are a lot of options you can use with the gcc compiler. For
example, if you want the output to have a name other than a.out, you can
use the -o option. The following shows a few examples:

`-o`: indicates that the next parameter is the name of the resulting program (or library). If this option is not specified, the compiled program will, for historic reasons, end up in a file called \"a.out\" or \"a.exe\" (for cygwin users).

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

`-Wall`: indicates that gcc should warn about many types of suspicious code that are likely to be incorrect.

You can use these options to create a program called \"helloworld\"
instead of \"a.out\" by typing:

`gcc -o helloworld hello.c -Wall`

Now you can run it by typing:

`./helloworld`

All the options are well documented in the manual[^2] for GCC.

#### On IDEs

If you are using an IDE you may have to select console project, and to
compile you just select build from the menu or the toolbar. The
executable will appear inside the project folder, but you should have a
menu button so you can just run the executable from the IDE. The process
is roughly the same on all IDEs.

## References

[^1]: <https://www.gnu.org/software/libc/manual/html_node/Exit-Status.html>

[^2]: <https://gcc.gnu.org/onlinedocs/>


# C Programming/Preliminaries

Before learning C syntax and programming constructs, it is important to
learn the meaning of a few key terms that are central in understanding
C.

## Block Structure, Statements, Whitespace, and Scope

Next we\'ll discuss the **basic structure** of a C program. If you\'re
familiar with PASCAL "wikilink"), you
may have heard it referred to as a **block-structured** language. C does
not have complete block structure (and you\'ll find out why when you go
over functions in detail) but it is still very important to understand
what blocks are and how to use them.

So what is in a **block**? Generally, a block consists of executable
**statements**.

But before we delve into blocks, let\'s examine statements. One way to
describe statements is they are the text (and surrounding whitespace)
the compiler will attempt to turn into executable instructions. A
simpler definition is statements are bits of code that do things. For
example:

``` c
int i = 6;
```

This **declares** an integer variable, which can be **accessed** with
the **identifier** \'i\', and **initializes** it to the value 6. The
various data types are introduced in the chapter
Variables.

You might have noticed the semicolon at the end of the statement.
Statements in C always end with a semicolon (;). Leaving off the
semicolon is a common mistake many people make, beginners and experts
alike! So until it becomes second nature, be sure to double check your
statements!

Since C is a \"free-format\" language, several statements can share a
single line in the source file, like this:

``` c
/* this declares the variables 'i', 'test', 'foo', and 'bar'
    note that ONLY the variable named 'bar' is initialized to six! */
int i, test, foo, bar = 6;
```

There are several kinds of statements. You\'ve already seen some of
them, such as the assignment (`i = 6;`). A substantial portion of this
book deals with statement construction.

Back to our discussion of blocks. In C, blocks begin with an opening
brace `"{"` and end with a closing brace `"}"`. Blocks can contain other
blocks which can contain their own blocks, and so on.

Let\'s look at a block example.

``` c
int main(void)
{
    /* this is a 'block' */
    int i = 5;

    {
        /* this is also a 'block', nested inside the outer block */
        int j = 6;
    }

    return 0;
}
```

You can use blocks with the preceding statements, such as the main
function declaration (and other statements we\'ve not yet covered), but
you can also use blocks by themselves.

**Whitespace** refers to the tab, space and newline characters that
separate the text characters that make up the source code.\
Like many things in life, it\'s hard to appreciate whitespace until
it\'s gone. To a C compiler, the source code

``` c
    printf("Hello world"); return 0;
```

is the same as

``` c
    printf("Hello world");
    return 0;
```

which is also the same as

``` c
    printf (
    "Hello world") ;

    return 0;
```

The compiler simply ignores most whitespace (except, for example, when
it separates `return` from `0`). However, it is common practice to use
spaces (or tabs) to organize source code for human readability.

Most of the time we do not want other functions or other programmer\'s
routines accessing data we are currently
manipulating, which is why it is important to understand the concept of
scope.

**Scope** describes the level at which a piece of data or a function is
visible. There are two types of scope in C, **local** and **global**.
When we speak of **global** scope, we\'re referring to something that
can be seen or manipulated from anywhere in the program. **Local** scope
applies to a program element that can be seen or manipulated only within
the block in which it was declared.

Let\'s look at some examples to get a better idea of scope.

``` c
int i = 5; /* this is a 'global' variable, it can be accessed from anywhere in the program */

/* this is a function, all variables inside of it
    are "local" to the function. */
int main(void)
{
    int i = 6; /* "local" 'i' is set to 6 */
    printf("%d\n", i); /* prints a '6' to the screen, instead of the global variable of 'i', which is 5 */

    return 0;
}
```

That shows an example of local and global. But what about different
scopes *inside* of functions?\
(you\'ll learn more about functions later, for now, just focus on the
\"main\" part.)

``` c
/* the main function */
int main(void)
{
    /* this is the beginning of a 'block', you read about those above */

    int i = 6; /* this is the first variable of this 'block', 'i' */

    {
        /* this is a new 'block', and because it's a different block, it has its own scope */

        /* this is also a variable called 'i', but in a different 'block',
            because it's in a different 'block' than the first variable named 'i', it doesn't affect the first one! */
        int i = 5;
        printf("%d\n", i); /* prints a '5' onto the screen */
    }
    /* now we're back into the first block */

    printf("%d\n", i); /* prints a '6' onto the screen */

    return 0;
}
```

## Basics of Using Functions

**Functions** are a big part of programming. A function is a special
kind of block that performs a well-defined task. If a function is
well-designed, it can enable a programmer to perform a task without
knowing anything about how the function works. The act of requesting a
function to perform its task is called a **function call**. Many
functions require a function call to hand it certain pieces of data
needed to perform its task; these are called **arguments**. Many
functions also return a value to the function call when they\'re
finished; this is called a **return value** (the return value in the
above program is **0**).

The things you need to know before calling a function are:

-   What the function does
-   The data type (discussed later) of the arguments and what they mean
-   The data type of the return value and what it means

Many functions use the return value for the result of a computation.
Some functions use the return value to indicate whether they
successfully completed their work. As you have seen in the intro
exercise, the `main` function uses a return value to provide an exit
status to the operating system.

All code other than global data definitions and declarations needs to be
a part of a function.

Usually, you\'re free to call a function whenever you wish to. The only
restriction is that every executable program needs to have one, and only
one, **main** function, which is where the program begins executing.

We will discuss functions in more detail in a later chapter, C
Programming/Procedures and
functions.

## The Standard Library

In 1983, when C was in the process of becoming standardized, the
American National Standards
Institute (ANSI)
formed a committee to establish a standard specification of C known as
\"ANSI C\". That standard specification created a basic set of functions
common to each implementation of C, which is referred to as the
Standard Library. The Standard
Library provides functions for tasks such as input/output, string
manipulation, mathematics, files, and memory allocation. The Standard
Library does not provide functions that are dependent on specific
hardware or operating systems, like graphics, sound, or networking. In
the \"Hello, World\" program, a Standard Library function is used
(`printf`) which outputs lines of text to the standard
output stream.

pl:C/Podstawy


# C Programming/Basics of compilation

Having covered the basic concepts of C programming, we can now briefly
discuss the process of *compilation*.

Like any programming language, C by itself is completely
incomprehensible to a microprocessor. Its
purpose is to provide an intuitive way for humans to provide
instructions that can be easily converted into machine code that *is*
comprehensible to a microprocessor. The ***compiler*** is what
translates our human-readable source code into machine code.

To those new to programming, this seems fairly simple. A naive compiler
might read in every source file, translate everything into machine code,
and write out an executable. That could work, but has two serious
problems. First, for a large project, the computer may not have enough
memory to read all of the source code at once. Second, if you make a
change to a single source file, you would have to recompile the *entire*
application.

To deal with these problems, compilers break the job into steps. For
each source file (each `.c` file), the compiler reads the file, reads
the files it references via the `#include` directive, and translates
them to machine code. The result of this is an \"object file\" (`.o`).
After all the object files are created, a \"linker\" program collects
all of the object files and writes the actual executable program. That
way, if you change one source file, only that file needs to be
recompiled, after which, the application will need to be re-linked.

Without going into details, it can be beneficial to have a superficial
understanding of the compilation process.

## Preprocessor

The preprocessor provides the ability for the inclusion of so called
header files, macro expansions, conditional compilation and line
control. These features can be accessed by inserting the appropriate
preprocessor directives into
your code. Before compiling the source code, a special program, called
the preprocessor, scans the source code for tokens, or special strings,
and replaces them with other strings or code according to specific
rules. The C preprocessor is not technically part of the C language and
is instead a tool offered by your compiler\'s software.

All preprocessor directives begin with the hash character (#). You can
see one preprocessor directive in the Hello world
program. Example:

``` c
 #include <stdio.h>
```

This directive causes the stdio header to be included into your program.
Other directives such as `#pragma` control compiler settings and macros.
The result of the preprocessing stage is a text string. You can think of
the preprocessor as a non-interactive text editor that modifies your
code to prepare it for compilation. The language of preprocessor
directives is agnostic to the grammar of C, so the C preprocessor can
also be used independently to process other kinds of text files.

## Syntax Checking

This step ensures that the code is valid and will sequence into an
executable program. Under most compilers, you may get messages or
warnings indicating potential issues with your program (such as a
conditional statement "wikilink")
always being true or false, etc.)

When an error is detected in the program, the compiler will normally
report the file name and line that is preventing compilation.

## Object Code

The compiler produces a machine code equivalent of the source code that
can be linked into the final program. At this point the code itself
can\'t be executed, as it requires linking to do so.

It\'s important to note after discussing the basics that compilation is
a \"one way street\". That is, compiling a C source file into machine
code is easy, but \"decompiling\" (turning machine code into the C
source that creates it) is not. Decompilers for C do exist, but the code
they create is hard to understand and only useful for reverse
engineering.

## Linking

Linking combines the separate object files into one complete program by
integrating libraries and the code and producing either an executable
program or a
library "wikilink"). Linking is performed by a
linker program, which is often part of a compiler suite.

Common errors during this stage are either missing or duplicate
functions.

## Automation

For large C projects, many programmers choose to automate compilation,
both in order to reduce user interaction requirements and to speed up
the process by recompiling only modified files.

Most Integrated Development Environments (IDE\'s) have some kind of
project management which makes such automation very easy. However, the
project management files are often usable only by users of the same
integrated development environment, so anyone desiring to modify the
project would need to use the same IDE.

On UNIX-like systems, make and Makefiles are often
used to accomplish the same. Make is traditional and flexible and is
available as one of the standard developer tools on most Unix and GNU
distributions.

Makefiles have been extended by the GNU
Autotools, composed of
Automake and
Autoconf for making software
compilable, testable, translatable and configurable on many types of
machines. Automake and Autoconf are described in detail in their
respective manuals.

The Autotools are often perceived to be complicated and various simpler
build systems have been developed. Many components of the GNOME
project now use the declarative Meson build
system which is less flexible, but instead
focuses on providing the features most commonly needed from a build
system in a simple way. Other popular build systems for programs written
in the C language include CMake and
Waf.

Once GCC is installed, it can be called with a list of c source files
that have been written but not yet compiled. e.g. if the file main.c
includes functions described in myfun.h and implemented in myfun_a.c and
myfun_b.c, then it is enough to write

` gcc   main.c myfun_a.c myfun_b.c `

myfun.h is included in main.c, but if it is in a separate header file
directory, then that directory can be listed after a \"-I \" switch.

In larger programs, Makefiles and GNU make program can compile c files
into intermediate files ending with suffix .o which can be linked by
GCC.

How to compile each object file is usually described in the Makefile
with the object file as a label ending with a colon followed by two
spaces (tabs often cause problems) followed by a list of other files
that are dependencies, e.g. .c files and .o files compiled in another
section, and on the next line, the invocation of GCC that is required.

Typing `man make` or `info make` often gives the information needed to
on how to use make, as well as GCC.

Although GCC has a lot of option switches, one often used is -g to
generate debugging information for gdb to allow gdb to show source code
during a step-through of the machine code program. gdb has an \'h\'
command that shows what it can do, and is usually started with \'gdb
a.out\' if a.out is the anonymous executable machine code file that was
compiled by GCC.

de:C-Programmierung:
Kompilierung
es:Programación_en_C/Compilar_un_programa
et:Programmeerimiskeel
C/Kompileerimine
fr:Programmation C-C%2B%2B/Modularité et
compilation
it:C/Compilatore e
precompilatore/Compilatore
pt:Programar em C/Utilizando um
compilador


# C Programming/Structure and style

## C Structure and Style

This is a basic introduction to good coding style in the C Programming
Language. It is designed to provide information on how to effectively
use indentation, comments, and other elements that will make your C code
more readable. It is not a tutorial on actual C programming.

As a beginning programmer, the point of creating structure in the
program code might not be clear, as the compiler doesn\'t care about the
difference. However, as programs become complex, chances are that
writing the program has become a joint effort. (Or others might want to
see how it was accomplished. Or you may have to read it again years
later.) Well-written code also helps you get an overview of what the
code does.

In the following sections, we will attempt to explain good programming
practices that will in turn make your programs clearer.

## Introduction

In C, programs are composed of statements. Statements are terminated
with a semi-colon, and are collected in sections known as functions. By
convention, a statement should be kept on its own line, as shown in the
example below:

``` c
 #include <stdio.h>

 int main(void) {
    printf("Hello, World!\n");
    return 0;
 }
```

The following block of code is essentially the same. While it contains
exactly the same code, and will compile and execute with the same
result, the removal of spacing causes an essential difference: it\'s
harder to read.

``` c
 #include <stdio.h>
 int main(void) {printf("Hello, World!\n");return 0;}
```

The simple use of indents and line breaks can greatly improve code
readability without impacting code performance. Readable code makes it
much easier to see where functions and procedures end and which lines
are part of which loops and procedures.

This lesson is going to focus on improving the coding style of an
example piece of code which applies a formula and prints the result.
Later, you\'ll see how to write code for such tasks in more detail. For
now, focus on how the code looks, not what it does.

## Line Breaks and Indentation

The addition of white space inside your code is arguably the most
important part of good code structure. Effective use of white space can
create a visual scale of how your code flows, which can be very
important when returning to your code when you want to maintain it.

### Line Breaks

With minimal line breaks, code is barely human-readable, and may be hard
to debug or understand:

``` {.c .numberLines}
#include <stdio.h>
int main(void) { int revenue = 80; int cost = 50; int roi; roi = (100 * (revenue - cost)) / cost; if (roi >= 0) { printf ("%d\n", roi); } return 0; }
```

Rather than putting everything on one line, it is much more readable to
break up long lines so that each statement and declaration goes on its
own line. After inserting line breaks, the code will look like this:

``` {.c .numberLines}
#include <stdio.h>
int main(void) {
int revenue = 80;
int cost = 50;
int roi;
roi = (100 * (revenue - cost)) / cost;
if (roi >= 0) {
printf ("%d\n", roi);
}
return 0;
}
```

### Blank Lines

Blank lines should be used to offset the main components of your code.
Always use them:

-   After preprocessor directives.
-   After new variables are declared.
-   Use your own judgment for finding other places where components
    should be separated.

Based on these two rules, there should now be at least two line breaks
added:

-   After line 1, because line 1 has a preprocessor directive.
-   After line 5, because line 5 contains a variable declaration.

This will make the code much more readable than it was before:

The following lines of code have line breaks between functions, but
without indentation.

``` {.c .numberLines}
#include <stdio.h>

int main(void) {

int revenue = 80;
int cost = 50;

int roi;

roi = (100 * (revenue - cost)) / cost;

if (roi >= 0) {
printf ("%d\n", roi);
}

return 0;
}
```

But it\'s still not as readable as it can be.

### Indentation

Although adding simple line breaks between key blocks of code can make
code easier to read, it provides no information about the block
structure of the program. Using the tab key can be very helpful.
Indentation visually separates paths of execution by moving their
starting points to a new column. This simple practice will make it much
easier to read and understand code. Indentation follows a fairly simple
rule:

-   All code inside a new block should be indented by one
    tab`<ref>`{=html}

Several programmers recommend \"use spaces for indentation. Do not use
tabs in your code. You should set your editor to emit spaces when you
hit the tab key.\"
1
2

Other programmers disagree.
3
4

Regardless of whether you prefer spaces or tabs, make sure you keep it
consistent within the projects you are working on. Mixing tabs and
spaces can cause code to become unreadable.

```{=html}
</ref>
```
more than the code in the previous path.

Based on the code from the previous section, there are two blocks
requiring indentation:

-   Lines 4 to 16
-   Line 13

``` {.c .numberLines}
#include <stdio.h>

int main(void) {

    int revenue = 80;
    int cost = 50;

    int roi;

    roi = (100 * (revenue - cost)) / cost;

    if (roi >= 0) {
        printf ("%d\n", roi);
    }

    return 0;
}
```

It is now fairly obvious as to which parts of the program fit inside
which blocks. You can tell which parts of the program the coder has
intended to be conditional, and which ones he or she has not. Although
it might not be immediately noticeable, once many nested paths get added
to the structure of the program, the use of indentation can be very
important. Thus, indentation makes the structure of your program clear.

It is claimed that research has shown that an indentation size between 2
to 4 characters is easier to read than 8 character indents[^1]. However,
an indent of 8 characters may still be in use for some systems[^2].

## Comments

Comments in code can be useful for a variety of purposes. They provide
the easiest way to set off specific parts of code (and their purpose);
as well as providing a visual \"split\" between various parts of your
code. Having good comments throughout your code will make it much easier
to remember what specific parts of your code do.

Comments in modern flavors of C (and many other languages) can come in
two forms:

``` {.c .numberLines}
// Single Line Comments  (added by C99 standard, famously known as c++ style of comments)
```

and

``` {.c .numberLines}
/* Multi-Line
Comments
(only form of comments supported by C89 standard)*/
```

Note that Single line comments are a more recent addition to C, so some
compilers may not support them. A recent version of
GCC will have no
problems supporting them.

This section is going to focus on the various uses of each form of
commentary.

### Single-line Comments

Single-line comments are most useful for simple \'side\' notes that
explain what certain parts of the code do. The best places to put these
comments are next to variable declarations, and next to pieces of code
that may need explanation. Comments should make clear the intention and
ideas behind the corresponding code. What is immediately obvious from
reading the code does not belong in a comment.

Based on our previous program, there are various good places to place
comments:

-   Line 5 and/or 6, to explain what \'int revenue\' and \'int cost\'
    represent,
-   Line 8, to explain what the variable \'roi\' is going to be used
    for,
-   Line 10, to explain the idea of the calculation,
-   Line 12, to explain the purpose of the \'if\'.

This will make our program look something like:

``` {.c .numberLines}
#include <stdio.h>

int main(void) {

    int revenue = 80;               // as of 2016
    int cost = 50;

    int roi;                        // return on investment in percent

    roi = (100 * (revenue - cost)) / cost;  // formula from accounting book

    if (roi >= 0) {                 // we don't care about negative roi
        printf ("%d\n", roi);
    }

    return 0;
}
```

### Multi-line Comments

Multi-line comments are most useful for long explanations of code. They
can be used as copyright/licensing notices, and they can also be used to
explain the purpose of a block of code. This can be useful for two
reasons: They make your functions easier to understand, and they make it
easier to spot errors in code. If you know what a block is *supposed* to
do, then it is much easier to find the piece of code that is responsible
if an error occurs.

As an example, suppose we had a program that was designed to print
\"Hello, World! \" a certain number of lines, a specified number of
times. There would be many for loops in this program. For this example,
we shall call the number of lines *i*, and the number of strings per
line as *j*.

A good example of a multi-line comment that describes \'for\' loop
*i*\'s purpose would be:

``` c
 /* For Loop (int i)
    Loops the following procedure i times (for number of lines).  Performs 'for' loop j on each loop,
    and prints a new line at end of each loop.
 */
```

This provides a good explanation of what *i*\'s purpose is, whilst not
going into detail of what *j* does. By going into detail over what the
specific path does (and not ones inside it), it will be easier to
troubleshoot the path.

Similarly, you should always include a multi-line comment before each
function, to explain the role, preconditions and postconditions of each
function. Always leave the technical details to the individual blocks
inside your program - this makes it easier to troubleshoot.

A function descriptor should look something like:

``` c
 /* Function : int hworld (int i,int j)
    Input    : int i (Number of lines), int j (Number of instances per line)
    Output   : 0 (on success)
    Procedure: Prints "Hello, World!" j times, and a new line to standard output over i lines.
 */
```

This system allows for an at-a-glance explanation of what the function
should do. You can then go into detail over how each aspect of the
program is achieved later on in the program.

Finally, if you like to have aesthetically-pleasing source code, the
multi-line comment system allows for the easy addition of comment boxes.
These make the comments stand out much more than they would otherwise.
They look like this:

``` c
 /***************************************
  *  This is a multi line comment
  *  That is nearly surrounded by a
  *  Cool, starry border!
  ***************************************/
```

Applied to our original program, we can now include a much more
descriptive and readable source code:

``` c
#include <stdio.h>

int main(void) {
    /************************************************************************************
     * Function: int main(void)
     * Input   : none
     * Output  : Returns 0 on success
     * Procedure: Prints 2016's return on investment in percent if it is not negative.
     ************************************************************************************/
    int revenue = 80;               // as of 2016
    int cost = 50;

    int roi;                        // return on investment in percent

    roi = (100 * (revenue - cost)) / cost;  // formula from accounting book

    if (roi >= 0) {                 // we don't care about negative roi
        printf ("%d\n", roi);
    }

    return 0;
}
```

This will allow any outside users of the program an easy way to
comprehend what the code functions are and how they operate. It also
inhibits uncertainty with other like-named functions.

A few programmers add a column of stars on the right side of a block
comment:

``` c
 /***************************************
  *  This is a multi line comment       *
  *  that is completely surrounded by a *
  *  cool, starry border!               *
  ***************************************/
```

But most programmers don\'t put any stars on the right side of a block
comment. They feel that aligning the right side is a waste of time.

Comments written in source files can be used for documenting source code
automatically by using popular tools like Doxygen.[^3][^4]

## References

-   Aladdin\'s C coding
    guidelines -
    A more definitive C coding guideline.
-   C/C++ Programming
    Styles
    GNU Coding styles & Linux Kernel Coding style

et:Programmeerimiskeel
C/Stiil

[^1]: <http://www.oualline.com/vim/vim-cook.html#drawing> Vim cookbook

[^2]: <https://www.kernel.org/doc/html/latest/process/coding-style.html>
    Linux Kernel Coding Style

[^3]: \"Coding Conventions for C++ and
    Java\"
    \"all the block comments illustrated in this document have no pretty
    stars on the right side of the block comment. This deliberate choice
    was made because aligning those pretty stars is a large waste of
    time and discourages the maintenance of in-line comments.\",

[^4]: c2:BigBlocksOfAsterisks,\"Code
    craft\"
    by Pete Goodliffe page 82,Falvotech \"C Programming Style
    Guide\",
    Fedora Directory Server Coding
    Style


# C Programming/Variables

Like most programming languages, C uses and processes **variables**. In
C, variables are human-readable names for the computer\'s memory
addresses used by a running program. Variables make it easier to store,
read and change the data within the computer\'s memory by allowing you
to associate easy-to-remember labels for the memory addresses that store
your program\'s data. The memory addresses associated with variables
aren\'t determined until after the program is compiled and running on
the computer.

At first, it\'s easiest to imagine variables as placeholders for values,
much like in mathematics. You can think of a variable as being
equivalent to its assigned value. So, if you have a variable *i* that is
**initialized** (set equal) to 4, then it follows that *i + 1* will
equal *5*. However, a skilled C programmer is more mindful of the
invisible layer of abstraction going on just under the hood: that a
variable is a stand-in for the memory address where the data can be
found, not the data itself. You will gain more clarity on this point
when you learn about **pointers**.

Since C is a relatively low-level programming language, before a C
program can utilize memory to store a variable it must claim the memory
needed to store the values for a variable. This is done by **declaring**
variables. Declaring variables is the way in which a C program shows the
number of variables it needs, what they are going to be named, and how
much memory they will need.

Within the C programming language, when managing and working with
variables, it is important to know the *type* of variables and the
*size* of these types. A type's size is the amount of computer memory
required to store one value of this type. Since C is a fairly low-level
programming language, the size of types can be specific to the hardware
and compiler used -- that is, how the language is made to work on one
type of machine can be different from how it is made to work on another.

All variables in C are **typed**. That is, every variable declared must
be assigned as a certain type of variable.

## Declaring, Initializing, and Assigning Variables

Here is an example of declaring an integer, which we\'ve called
`some_number`. (Note the semicolon at the end of the line; that is how
your compiler separates one program *statement* from another.)

``` c
int some_number;
```

This statement tells the compiler to create a variable called
`some_number` and associate it with a memory location on the computer.
We also tell the compiler the type of data that will be stored at that
address, in this case an `int`eger. Note that in C we must specify the
type of data that a variable will store. This lets the compiler know how
much total memory to set aside for the data (on most modern machines an
`int` is 4 bytes in length). We\'ll look at other data types in the next
section.

Multiple variables can be declared with one statement, like this:

``` c
int anumber, anothernumber, yetanothernumber;
```

In early versions of C, variables had to be declared at the beginning of
a block. In C99 it is allowed to mix declarations and statements
arbitrarily -- but doing so is not usual, because it is rarely
necessary, some compilers still don't support C99 (portability), and it
may, because it is uncommon yet, irritate fellow programmers
(maintainability).

After declaring variables, you can assign a value to a variable later on
using a statement like this:

``` c
some_number = 3;
```

The assignment of a value to a variable is called *initialization*. The
above statement directs the compiler to insert an integer representation
of the number \"3\" into the memory address associated with
`some_number`. We can save a bit of typing by declaring *and* assigning
data to a memory address at the same time:

``` c
int some_new_number = 4;
```

You can also assign variables to the value of other variable, like so:

``` c
some_number = some_new_number;
```

Or assign multiple variables the same value with one statement:

``` c
anumber = anothernumber = yetanothernumber = 8;
```

This is because the assignment `x = y` returns the value of the
assignment, y. For example, `some_number = 4` returns 4. That said,
`x = y = z` is really a shorthand for `x = (y = z)`.

### Naming Variables

Variable names in C are made up of letters (upper and lower case) and
digits. The underscore character (\"\_\") is also permitted. Names must
not begin with a digit. Unlike some languages (such as
Perl and some
BASIC dialects), C does not
use any special prefix characters on variable names.

Some examples of valid (but not very descriptive) C variable names:

``` c
foo
Bar
BAZ
foo_bar
_foo42
_
QuUx
```

Some examples of invalid C variable names:

``` c
2foo    (must not begin with a digit)
my foo  (spaces not allowed in names)
$foo    ($ not allowed -- only letters, and _)
while   (language keywords cannot be used as names)
```

As the last example suggests, certain words are reserved as keywords in
the language, and these cannot be used as variable names.

It is not allowed to use the same name for multiple variables in the
same scope. When working with
other developers, you should therefore take steps to avoid using the
same name for global variables or function names. Some large projects
adhere to naming guidelines[^1] to avoid duplicate names and for
consistency.

In addition there are certain sets of names that, while not language
keywords, are reserved for one reason or another. For example, a C
compiler might use certain names \"behind the scenes\", and this might
cause problems for a program that attempts to use them. Also, some names
are reserved for possible future use in the C standard library. The
rules for determining exactly what names are reserved (and in what
contexts they are reserved) are too complicated to describe
here, and as a beginner you don\'t need to worry
about them much anyway. For now, just avoid using names that begin with
an underscore character.

The naming rules for C variables also apply to naming other language
constructs such as function names, struct tags, and macros, all of which
will be covered later.

## Literals

Anytime within a program in which you specify a value explicitly instead
of referring to a variable or some other form of data, that value is
referred to as a **literal**. In the initialization example above, 3 is
a literal. Literals can either take a form defined by their type (more
on that soon), or one can use hexadecimal (hex) notation to directly
insert data into a variable regardless of its
type. Hex numbers are always preceded with *0x*.
For now, though, you probably shouldn\'t be too concerned with hex.

## The Four Basic Data Types

In Standard C there are four basic data types. They are **`int`**,
**`char`**, **`float`**, and **`double`**.

### The `int` type

The `int` type stores integers in the form of \"whole numbers\". An
integer is typically the size of one machine word, which on most modern
home PCs is 32 bits (4 octets). Examples of literals are whole numbers
(integers) such as 1, 2, 3, 10, 100\... When `int` is 32 bits (4
octets), it can store any whole number (integer) between -2147483648 and
2147483647. A 32 bit word (number) has the possibility of representing
any one number out of 4294967296 possibilities (2 to the power of 32).

If you want to declare a new int variable, use the `int` keyword. For
example:

``` c
int numberOfStudents, i, j = 5;
```

In this declaration we declare 3 variables, numberOfStudents, i and j, j
here is assigned the literal 5.

### The `char` type

The `char` type is capable of holding any member of the execution
character
set.
It stores the same kind of data as an `int` (i.e. integers), but
typically has a size of one byte. The size of a byte is specified by the
macro `CHAR_BIT` which specifies the number of bits in a char (byte). In
standard C it never can be less than 8 bits. A variable of type `char`
is most often used to store character data, hence its name. Most
implementations use the ASCII character set as the
execution character set, but it\'s best not to know or care about that
unless the actual values are important.

Examples of character literals are \'a\', \'b\', \'1\', etc., as well as
some special characters such as \'`\0`\' (the null character) and
\'`\n`\' (newline, recall \"Hello, World\"). Note that the `char` value
must be enclosed within single quotations.

When we initialize a character variable, we can do it two ways. One is
preferred, the other way is ***bad*** programming practice.

The first way is to write:

``` c
char letter1 = 'a';
```

This is *good* programming practice in that it allows a person reading
your code to understand that letter1 is being initialized with the
letter \'a\' to start off with.

The second way, which should *not* be used when you are coding letter
characters, is to write:

``` c
char letter2 = 97; /* in ASCII, 97 = 'a' */
```

This is considered by some to be extremely ***bad*** practice, if we are
using it to store a character, not a small number, in that if someone
reads your code, most readers are forced to look up what character
corresponds with the number 97 in the encoding scheme. In the end,
`letter1` and `letter2` store both the same thing -- the letter \'a\',
but the first method is clearer, easier to debug, and much more
straightforward.

One important thing to mention is that characters for numerals are
represented differently from their corresponding number, i.e. \'1\' is
not equal to 1. In short, any single entry that is enclosed within
\'single quotes\'.

There is one more kind of literal that needs to be explained in
connection with chars: the **string literal**. A string is a series of
characters, usually intended to be displayed. They are surrounded by
double quotations (\" \", not \' \'). An example of a string literal is
the \"Hello, World!\\n\" in the \"Hello, World\" example.

The string literal is assigned to a character
`<b>`{=html}array`</b>`{=html}, arrays are described later. Example:

``` c
const char MY_CONSTANT_PEDANTIC_ITCH[] = "learn the usage context.\n";
printf("Square brackets after a variable name means it is a pointer to a string of memory blocks the size of the type of the array element.\n");
```

### The `float` type

`float` is short for **floating point**. It stores inexact
representations of real numbers, both integer and non-integer values. It
can be used with numbers that are much greater than the greatest
possible `int`. `float` literals must be suffixed with F or f. Examples
are: 3.1415926f, 4.0f, 6.022e+23f.

It is important to note that floating-point numbers are inexact. Some
numbers like 0.1f cannot be represented exactly as `float`s but will
have a small error. Very large and very small numbers will have less
precision and arithmetic operations are sometimes not associative or
distributive because of a lack of precision. Nonetheless, floating-point
numbers are most commonly used for approximating real numbers and
operations on them are efficient on modern microprocessors.[^2]
Floating-point arithmetic is
explained in more detail on Wikipedia.

`float` variables can be declared using the `float` keyword. A `float`
is only one machine word in size. Therefore, it is used when less
precision than a double provides is required.

### The `double` type

The `double` and `float` types are very similar. The `float` type allows
you to store single-precision floating point numbers, while the `double`
keyword allows you to store double-precision floating point numbers --
real numbers, in other words. Its size is typically two machine words,
or 8 bytes on most machines. Examples of `double` literals are
3.1415926535897932, 4.0, 6.022e+23 (scientific
notation). If you use 4 instead of
4.0, the 4 will be interpreted as an `int`.

The distinction between floats and doubles was made because of the
differing sizes of the two types. When C was first used, space was at a
minimum and so the judicious use of a float instead of a double saved
some memory. Nowadays, with memory more freely available, you rarely
need to conserve memory like this -- it may be better to use doubles
consistently. Indeed, some C implementations use doubles instead of
floats when you declare a float variable.

If you want to use a double variable, use the `double` keyword.

## `sizeof`

If you have any doubts as to the amount of memory actually used by any
variable (and this goes for types we\'ll discuss later, also), you can
use the **`sizeof`** operator to find out for sure. (For completeness,
it is important to mention that `sizeof` is a unary
operator, not a function.) Its syntax is:

``` c
sizeof object
sizeof(type)
```

The two expressions above return the size of the object and type
specified, in bytes. The return type is `size_t` (defined in the header
`<stddef.h>`) which is an unsigned value. Here\'s an example usage:

``` c
size_t size;
int i;
size = sizeof(i);
```

`size` will be set to 4, assuming `CHAR_BIT` is defined as 8, and an
integer is 32 bits wide. The value of `sizeof`\'s result is the number
of bytes.

Note that when `sizeof` is applied to a `char`, the result is 1; that
is:

``` c
sizeof(char)
```

always returns 1.

## Data type modifiers

One can alter the data storage of any data type by preceding it with
certain modifiers.

**`long`** and **`short`** are modifiers that make it possible for a
data type to use either more or less memory. The `int` keyword need not
follow the `short` and `long` keywords. This is most commonly the case.
A `short` can be used where the values fall within a lesser range than
that of an `int`, typically -32768 to 32767. A `long` can be used to
contain an extended range of values. It is not guaranteed that a `short`
uses less memory than an `int`, nor is it guaranteed that a `long` takes
up more memory than an `int`. It is only guaranteed that sizeof(short)
\<= sizeof(int) \<= sizeof(long). Typically a `short` is 2 bytes, an
`int` is 4 bytes, and a `long` either 4 or 8 bytes. Modern C compilers
also provide `long long` which is typically an 8 byte integer.

In all of the types described above, one bit is used to indicate the
sign (positive or negative) of a value. If you decide that a variable
will never hold a negative value, you may use the **`unsigned`**
modifier to use that one bit for storing other data, effectively
doubling the range of values while mandating that those values be
positive. The `unsigned` specifier also may be used without a trailing
`int`, in which case the size defaults to that of an `int`. There is
also a **`signed`** modifier which is the opposite, but it is not
necessary, except for certain uses of `char`, and seldom used since all
types (except `char`) are signed by default.

The `long` modifier can also be used with `double` to create a
`long double` type. This floating-point type may (but is not required
to) have greater precision than the `double` type.

To use a modifier, just declare a variable with the data type and
relevant modifiers:

``` c
unsigned short int usi;  /* fully qualified -- unsigned short int */
short si;                /* short int */
unsigned long uli;       /* unsigned long int */
```

## `const` qualifier

When the **`const`** qualifier is used, the declared variable must be
initialized at declaration. It is then not allowed to be changed.

While the idea of a variable that never changes may not seem useful,
there are good reasons to use `const`. For one thing, many compilers can
perform some small optimizations on data when it knows that data will
never change. For example, if you need the value of π in your
calculations, you can declare a const variable of `pi`, so a program or
another function written by someone else cannot change the value of
`pi`.

Note that a Standard conforming compiler must issue a warning if an
attempt is made to change a `const` variable - but after doing so the
compiler is free to ignore the `const` qualifier.

## Magic numbers

When you write C programs, you may be tempted to write code that will
depend on certain numbers. For example, you may be writing a program for
a grocery store. This complex program has thousands upon thousands of
lines of code. The programmer decides to represent the cost of a can of
corn, currently 99 cents, as a literal throughout the code. Now, assume
the cost of a can of corn changes to 89 cents. The programmer must now
go in and manually change each entry of 99 cents to 89. While this is
not that big a problem, considering the \"global find-replace\" function
of many text editors, consider another problem: the cost of a can of
green beans is also initially 99 cents. To reliably change the price,
you have to look at every occurrence of the number 99.

C possesses certain functionality to avoid this. This functionality is
approximately equivalent, though one method can be useful in one
circumstance, over another.

### Using the `const` keyword

The `const` keyword helps eradicate **magic numbers**. By declaring a
variable `const corn` at the beginning of a block, a programmer can
simply change that const and not have to worry about setting the value
elsewhere.

There is also another method for avoiding magic numbers. It is much more
flexible than `const`, and also much more problematic in many ways. It
also involves the preprocessor, as opposed to the compiler. Behold\...

### `#define`

When you write programs, you can create what is known as a *macro*, so
when the computer is reading your code, it will replace all instances of
a word with the specified expression.

Here\'s an example. If you write

``` c
#define PRICE_OF_CORN 0.99
```

when you want to, for example, print the price of corn, you use the word
`PRICE_OF_CORN` instead of the number 0.99 -- the preprocessor will
replace all instances of `PRICE_OF_CORN` with 0.99, which the compiler
will interpret as the literal `double` 0.99. The preprocessor performs
substitution, that is, `PRICE_OF_CORN` is replaced by 0.99 so this means
there is no need for a semicolon.

It is important to note that `#define` has basically the same
functionality as the \"find-and-replace\" function in a lot of text
editors/word processors.

For some purposes, `#define` can be harmfully used, and it is usually
preferable to use `const` if `#define` is unnecessary. It is possible,
for instance, to `#define`, say, a macro `DOG` as the number 3, but if
you try to print the macro, thinking that `DOG` represents a string that
you can show on the screen, the program will have an error. `#define`
also has no regard for type. It disregards the structure of your
program, replacing the text *everywhere* (in effect, disregarding
scope), which could be advantageous in some circumstances, but can be
the source of problematic bugs.

You will see further instances of the `#define` directive later in the
text. It is good convention to write `#define`d words in all capitals,
so a programmer will know that this is not a variable that you have
declared but a `#define`d macro. It is not necessary to end a
preprocessor directive such as `#define` with a semicolon; in fact, some
compilers may warn you about unnecessary tokens in your code if you do.

## Scope

In the Basic Concepts section, the concept of scope was introduced. It
is important to revisit the distinction between local types and global
types, and how to declare variables of each. To declare a local
variable, you place the declaration at the beginning (i.e. before any
non-declarative statements) of the block to which the variable is deemed
to be local. To declare a global variable, declare the variable outside
of any block. If a variable is global, it can be read, and written, from
anywhere in your program.

Global variables are not considered good programming practice, and
should be avoided whenever possible. They inhibit code readability,
create naming conflicts, waste memory, and can create difficult-to-trace
bugs. Excessive usage of globals is usually a sign of laziness or poor
design. However, if there is a situation where local variables may
create more obtuse and unreadable code, there\'s no shame in using
globals.

## Other Modifiers

Included here, for completeness, are more of the modifiers that standard
C provides. For the beginning programmer, *static* and *extern* may be
useful. *volatile* is more of interest to advanced programmers.
*register* and *auto* are largely deprecated and are generally not of
interest to either beginning or advanced programmers.

### static

**`static`** is sometimes a useful keyword. It is a common misbelief
that the only purpose is to make a variable stay in memory.

When you declare a function or global variable as *static*, you cannot
access the function or variable through the extern (see below) keyword
from other files in your project. This is called *static linkage*.

When you declare a local variable as *static*, it is created just like
any other variable. However, when the variable goes out of scope (i.e.
the block it was local to is finished) the variable stays in memory,
retaining its value. The variable stays in memory until the program
ends. While this behaviour resembles that of global variables, static
variables still obey scope rules and therefore cannot be accessed
outside of their scope. This is called *static storage duration*.

Variables declared static are initialized to zero (or for pointers,
NULL[^3][^4]) by default. They can be initialized explicitly on
declaration to any *constant* value. The initialization is made just
once, at compile time.

You can use static in (at least) two different ways. Consider this code,
and imagine it is in a file called jfile.c:

``` c
#include <stdio.h>

static int j = 0;

void up(void)
{
   /* k is set to 0 when the program starts. The line is then "ignored"
    * for the rest of the program (i.e. k is not set to 0 every time up()
    * is called)
    */
   static int k = 0;
   j++;
   k++;
   printf("up() called.   k= %2d, j= %2d\n", k , j);
}

void down(void)
{
   static int k = 0;
   j--;
   k--;
   printf("down() called. k= %2d, j= %2d\n", k , j);
}

int main(void)
{
   int i;

   /* call the up function 3 times, then the down function 2 times */
   for (i = 0; i < 3; i++)
      up();
   for (i = 0; i < 2; i++)
      down();

   return 0;
}
```

The `j` variable is accessible by both up and down and retains its
value. The `k` variables also retain their value, but they are two
different variables, one in each of their scopes. Static variables are a
good way to implement encapsulation, a term from the object-oriented way
of thinking that effectively means not allowing changes to be made to a
variable except through function calls.

Running the program above will produce the following output:

``` c
up() called.   k=  1, j=  1
up() called.   k=  2, j=  2
up() called.   k=  3, j=  3
down() called. k= -1, j=  2
down() called. k= -2, j=  1
```

**Features of `static` variables :**

`    1. Keyword used        - `**`static`**\
`    2. Storage             - Memory`\
`    3. Default value       - Zero`\
`    4. Scope               - Local to the block in which it is declared`\
`    5. Lifetime            - Value persists between different function calls`\
`    6. Keyword optionality - Mandatory to use the keyword`

### extern

**`extern`** is used when a file needs to access a variable in another
file that it may not have `#include`d directly. Therefore, *extern* does
not allocate memory for the new variable, it just provides the compiler
with sufficient information to access a variable declared in another
file.

**Features of `extern` variable :**

`    1. Keyword used        - `**`extern`**\
`    2. Storage             - Memory`\
`    3. Default value       - Zero`\
`    4. Scope               - Global (all over the program)`\
`    5. Lifetime            - Value persists till the program's execution comes to an end`\
`    6. Keyword optionality - Optional if declared outside all the functions`

### volatile

**`volatile`** is a special type of modifier which informs the compiler
that the value of the variable may be changed by external entities other
than the program itself. This is necessary for certain programs compiled
with optimizations -- if a variable were not defined `volatile` then the
compiler may assume that certain operations involving the variable are
safe to optimize away when in fact they aren\'t. *volatile* is
particularly relevant when working with embedded systems (where a
program may not have complete control of a variable) and multi-threaded
applications.

### auto

**`auto`** is a modifier which specifies an \"automatic\" variable that
is automatically created when in scope and destroyed when out of scope.
If you think this sounds like pretty much what you\'ve been doing all
along when you declare a variable, you\'re right: all declared items
within a block are implicitly \"automatic\". For this reason, the *auto*
keyword is more like the answer to a trivia question than a useful
modifier, and there are lots of very competent programmers that are
unaware of its existence.

**Features of `automatic` variables :**

`    1. Keyword used        - `**`auto`**\
`    2. Storage             - Memory`\
`    3. Default value       - Garbage value (random value)`\
`    4. Scope               - Local to the block in which it is defined`\
`    5. Lifetime            - Value persists while the control remains within the block`\
`    6. Keyword optionality - Optional`

### register

**`register`** is a hint to the compiler to attempt to optimize the
storage of the given variable by storing it in a register of the
computer\'s CPU when the program is run. Most optimizing compilers do
this anyway, so use of this keyword is often unnecessary. In fact, ANSI
C states that a compiler can ignore this keyword if it so desires -- and
many do. Microsoft Visual C++ is an example of an implementation that
completely ignores the *register* keyword.

**Features of `register` variables :**

`    1. Keyword used        - `**`register`**\
`    2. Storage             - CPU registers (values can be retrieved faster than from memory)`\
`    3. Default value       - Garbage value`\
`    4. Scope               - Local to the block in which it is defined`\
`    5. Lifetime            - Value persists while the control remains within the block`\
`    6. Keyword optionality - Mandatory to use the keyword`

### Concepts

-   Variables
-   Types
-   Data Structures
-   Arrays

### In this section

-   C variables
    -   C arrays

## References

de:C-Programmierung: Variablen und
Konstanten
et:Programmeerimiskeel
C/Muutujad
fi:C/Muuttujat fr:Programmation C/Bases du
langage
it:C/Variabili, operatori e
costanti/Variabili
ja:C言語 変数
pl:C/Zmienne pt:Programar em
C/Variáveis

[^1]: Examples of naming guidelines are those of the GNOME
    Project
    or the parts of the Python
    interpreter that are
    written in C.

[^2]: Representations of real numbers other than floating-point numbers
    exist but are not fundamental data types in C. Some C compilers
    support fixed-point
    arithmetic data types, but
    these are not part of standard C. Libraries such as the GNU
    Multiple Precision Arithmetic
    Library
    offer more data types for real numbers and very large numbers.

[^3]: 1 - What is NULL and how is it
    defined?

[^4]: 2 - NULL or 0, which should
    you use?


# C Programming/Operators and type casting

## Operators and Assignments

C has a wide range of operators that make simple math easy to handle.
The list of operators grouped into precedence levels is as follows:

### Primary expressions

*Identifiers* are names of things in C, and consist of either a letter
or an underscore ( `_` ) optionally followed by letters, digits, or
underscores. An identifier (or variable name) is a primary expression,
provided that it has been declared as designating an object (in which
case it is an lvalue \[a value that can be used as the left side of an
assignment expression\]) or a function (in which case it is a function
designator).

A *constant* is a primary expression. Its type depends on its form and
value. The types of constants are character constants (e.g. `' '` is a
space), integer constants (e.g. `2`), floating-point constants (e.g.
`0.5`), and enumerated constants that have been previously defined via
`enum`.

A *string literal* is a primary expression. It consists of a string of
characters within double quotes ( `"` ).

A parenthesized expression is a primary expression. It consists of an
expression within parentheses ( `(` `)` ). Its type and value are those
of the non-parenthesized expression within the parentheses.

In C11, an expression that starts with `_Generic` followed by (, an
initial expression, a list of values of the form *type: expression*
where type is either a named type or the keyword default, and )
constitutes a primary expression. The value is the expression that
follows the type of the initial expression or the default if not found.

### Postfix operators

First, a primary expression is also a postfix expression. The following
expressions are also postfix expressions:

A postfix expression followed by a left square bracket (`[`), an
expression, and a right square bracket (`]`) in sequence constitutes an
invocation of the *array subscript operator*. One of the expressions
shall have type \"pointer to object `<i>`{=html}type`</i>`{=html}\" and
the other shall have an integer type; the result type is
`<i>`{=html}type`</i>`{=html}. Successive array subscript operators
designate an element of a multidimensional array.

A postfix expression followed by parentheses or an optional
parenthesized argument list indicates an invocation of the *function
call operator*. The value of the function call operator is the return
value of the function called with the provided arguments. The parameters
to the function are copied on the stack **by value** (or at least the
compiler acts as if that is what happens; if the programmer wanted the
parameter to be copied by reference, then it is easier to pass the
address of the area to be modified by value, then the called function
can access the area through the respective pointer). The trend for
compilers is to pass the parameters from right to left onto the stack,
but this is not universal.

A postfix expression followed by a dot (`.`) followed by an identifier
selects a member from a structure or union; a postfix expression
followed by an arrow (`->`) followed by an identifier selects a member
from a structure or union who is pointed to by the pointer on the
left-hand side of the expression.

A postfix expression followed by the increment or decrement operators
(`++` or `--` respectively) indicates that the variable is to be
incremented or decremented as a side effect. The value of the expression
is the value of the postfix expression *before* the increment or
decrement. These operators only work on integers and pointers.

### Unary expressions

First, a postfix expression is a unary expression. The following
expressions are all unary expressions:

The increment or decrement operators followed by a unary expression is a
unary expression. The value of the expression is the value of the unary
expression *after* the increment or decrement. These operators only work
on integers and pointers.

The following operators followed by a cast expression are unary
expressions:

`Operator     Meaning`\
`========     =======`\
`   &         Address-of; value is the location of the operand`\
`   *         Contents-of; value is what is stored at the location`\
`   -         Negation`\
`   +         Value-of operator`\
`   !         Logical negation ( (!E) is equivalent to (0==E) )`\
`   ~         Bit-wise complement`

The keyword `sizeof` followed by a unary expression is a unary
expression. The value is the size of the type of the expression in
bytes. The expression is not evaluated.

The keyword `sizeof` followed by a parenthesized type name is a unary
expression. The value is the size of the type in bytes.

### Cast operators

A unary expression is also a cast expression.

A parenthesized type name followed by any expression, including
literals, is a cast expression. The parenthesized type name has the
effect of forcing the cast expression into the type specified by the
type name in parentheses. For arithmetic types, this either does not
change the value of the expression, or truncates the value of the
expression if the expression is an integer and the new type is smaller
than the previous type.

An example of casting an int as a float:

``` C
int i = 5;
printf("%f\n", (float) i / 2); // Will print out:  2.500000
```

### Multiplicative and additive operators

First, a multiplicative expression is also a cast expression, and an
additive expression is also a multiplicative expression. This follows
the precedence that multiplication happens before addition.

In C, simple math is very easy to handle. The following operators exist:
**+** (addition), **-** (subtraction), **\*** (multiplication), /
(division), and **%** (modulus); You likely know all of them from your
math classes - except, perhaps, modulus. It returns the **remainder** of
a division (e.g. 5 % 2 = 1). (Modulus is not defined for floating-point
numbers, but the *math.h* library has an *fmod* function.)

Care must be taken with the modulus, because it\'s not the equivalent of
the mathematical modulus: (-5) % 2 is not 1, but -1. Division of
integers will return an integer, and the division of a negative integer
by a positive integer will round towards zero instead of rounding down
(e.g. (-5) / 3 = -1 instead of -2). However, it is always true that for
all integer a and nonzero integer b, `((a / b) * b) + (a % b) == a`.

There is no inline operator to do exponentiation (e.g. 5 \^ 2 is **not**
25 \[it is 7; **\^** is the exclusive-or operator\], and 5 \*\* 2 is an
error), but there is a power
function.

The mathematical order of operations does apply. For example (2 + 3) \*
2 = 10 while 2 + 3 \* 2 = 8. Multiplicative operators have precedence
over additive operators.

``` c
#include <stdio.h>

int main(void)
{
int i = 0, j = 0;

    /* while i is less than 5 AND j is less than 5, loop */
    while( (i < 5) && (j < 5) )
    {
        /* postfix increment, i++
         *     the value of i is read and then incremented
         */
        printf("i: %d\t", i++);

        /*
         * prefix increment, ++j
         *     the value of j is incremented and then read
         */
        printf("j: %d\n", ++j);
    }

    printf("At the end they have both equal values:\ni: %d\tj: %d\n", i, j);

    getchar(); /* pause */
    return 0;
}
```

will display the following:

    i: 0    j: 1
    i: 1    j: 2
    i: 2    j: 3
    i: 3    j: 4
    i: 4    j: 5
    At the end they have both equal values:
    i: 5    j: 5

### The shift operators (which may be used to rotate bits)

A shift expression is also an additive expression (meaning that the
shift operators have a precedence just below addition and subtraction).

Shift functions are often used in low-level I/O hardware interfacing.
Shift and rotate functions are heavily used in cryptography and software
floating point emulation. Other than that, shifts can be used in place
of division or multiplication by a power of two. Many processors have
dedicated function blocks to make these operations fast \-- see
Microprocessor Design/Shift and Rotate
Blocks. On
processors which have such blocks, most C compilers compile shift and
rotate operators to a single assembly-language instruction \-- see X86
Assembly/Shift and Rotate.

#### shift left

The `<<` operator shifts the binary representation to the left, dropping
the most significant bits and appending it with zero bits. The result is
equivalent to multiplying the integer by a power of two.

#### unsigned shift right

The unsigned shift right operator, also sometimes called the logical
right shift operator. It shifts the binary representation to the right,
dropping the least significant bits and prepending it with zeros. The
`>>` operator is equivalent to division by a power of two for unsigned
integers.

#### signed shift right

The signed shift right operator, also sometimes called the arithmetic
right shift operator. It shifts the binary representation to the right,
dropping the least significant bit, but prepending it with copies of the
original sign bit. The `>>` operator is not equivalent to division for
signed integers.

In C, the behavior of the `>>` operator depends on the data type it acts
on. Therefore, a signed and an unsigned right shift looks exactly the
same, but produces a different result in some cases.

#### rotate right

Contrary to popular belief, it is possible to write C code that compiles
down to the \"rotate\" assembly language instruction (on CPUs that have
such an instruction).

Most compilers recognize this idiom:

``` c
  unsigned int x;
  unsigned int y;
  /* ... */
  y = (x >> shift) | (x << (32 - shift));
```

and compile it to a single 32 bit rotate instruction. [^1] [^2]

On some systems, this may be \"#define\"ed as a macro or defined as an
inline function called something like \"rightrotate32\" or \"rotr32\" or
\"ror32\" in a standard header file like \"bitops.h\". [^3]

#### rotate left

Most compilers recognize this idiom:

``` c
  unsigned int x;
  unsigned int y;
  /* ... */
  y = (x << shift) | (x >> (32 - shift));
```

and compile it to a single 32 bit rotate instruction.

On some systems, this may be \"#define\"ed as a macro or defined as an
inline function called something like \"leftrotate32\" or \"rotl32\" in
a header file like \"bitops.h\".

### Relational and equality operators

A relational expression is also a shift expression; an equality
expression is also a relational expression.

The relational binary operators `<` (less than), `>` (greater than),
`<=` (less than or equal), and `>=` (greater than or equal) operators
return a value of 1 if the result of the operation is true, 0 if false.
The result of these operators is type `int`.

The equality binary operators `==` (equals) and `!=` (not equals)
operators are similar to the relational operators except that their
precedence is lower. They also return a value of 1 if the result of the
operation is true and 0 if it is false.

One thing with floating-point numbers and equality operators: Because
floating-point operations can produce approximations (e.g. 0.1 is a
repeating decimal in binary, so 0.1 \* 10.0 is hardly ever 1.0), it is
unwise to use the `==` operator with floating-point numbers. Instead, if
a and b are the numbers to compare, compare `fabs (a - b)` to a fudge
factor.

### Bitwise operators

The bitwise operators are `&` (and), `^` (exclusive or) and `|`
(inclusive or). The `&` operator has higher precedence than `^`, which
has higher precedence than `|`.

The values being operated upon must be integral; the result is integral.

One use for the bitwise operators is to emulate bit flags. These flags
can be set with OR, tested with AND, flipped with XOR, and cleared with
AND NOT. For example:

``` c
/* This code is a sample for bitwise operations.  */
#define BITFLAG1    (1)
#define BITFLAG2    (2)
#define BITFLAG3    (4) /* They are powers of 2 */

unsigned bitbucket = 0U;    /* Clear all */
bitbucket |= BITFLAG1;      /* Set bit flag 1 */
bitbucket &= ~BITFLAG2;     /* Clear bit flag 2 */
bitbucket ^= BITFLAG3;      /* Flip the state of bit flag 3 from off to on or
                               vice versa */
if (bitbucket & BITFLAG3) {
  /* bit flag 3 is set */
} else {
  /* bit flag 3 is not set */
}
```

### Logical operators

The logical operators are `&&` (and), and `||` (or). Both of these
operators produce 1 if the relationship is true and 0 for false. Both of
these operators short-circuit; if the result of the expression can be
determined from the first operand, the second is ignored. The `&&`
operator has higher precedence than the `||` operator.

`&&` is used to evaluate expressions left to right, and returns a 1 if
*both* statements are true, 0 if either of them are false. If the first
expression is false, the second is not evaluated.

``` c

  int x = 7;
  int y = 5;
  if(x == 7 && y == 5) {
      ...
  }
```

Here, the `&&` operator checks the left-most expression, then the
expression to its right. If there were more than two expressions chained
(e.g. `x && y && z`), the operator would check `x` first, then y (if `x`
is nonzero), then continue rightwards to z if neither x or y is zero.
Since both statements return true, the `&&` operator returns true, and
the code block is executed.

``` c

    if(x == 5 && y == 5) {
        ...
    }
```

The && operator checks in the same way as before, and finds that the
first expression is false. The && operator stops evaluating as soon as
it finds a statement to be false, and returns a false.

`||` is used to evaluate expressions left to right, and returns a 1 if
*either* of the expressions are true, 0 if both are false. If the first
expression is true, the second expression is not evaluated.

``` c

    /* Use the same variables as before. */
    if(x == 2 || y == 5) { // the || statement checks both expressions, finds that the latter is true, and returns true
        ...
    }
```

The `||` operator here checks the left-most expression, finds it false,
but continues to evaluate the next expression. It finds that the next
expression returns true, stops, and returns a 1. Much how the `&&`
operator ceases when it finds an expression that returns false, the `||`
operator ceases when it finds an expression that returns true.

It is worth noting that C does not have Boolean values (true and false)
commonly found in other languages. It instead interprets a 0 as false,
and any nonzero value as true.

### Conditional operators

The ternary `?:` operator is the conditional operator. The expression
`(x ? y : z)` has the value of `y` if `x` is nonzero, `z` otherwise.

Example:

``` c

int x = 0;
int y;
y = (x ? 10 : 6); /* The parentheses are technically not necessary as assignment
                     has a lower precedence than the conditional operator, but
                     it's there for clarity.  */
```

The expression `x` evaluates to 0. The ternary operator then looks for
the \"if-false\" value, which in this case, is 6. It returns that, so
`y` is equal to six. Had `x` been a non-zero, then the expression would
have returned a 10.

### Assignment operators

The assignment operators are `=`, `*=`, `/=`, `%=`, `+=`, `-=`, `<<=`,
`>>=`, `&=`, `^=`, and `|=` . The `=` operator stores the value of the
right operand into the location determined by the left operand, which
must be an lvalue (a value that has an address, and
therefore can be assigned to).

For the others, `x op= y` is shorthand for `x = x op (y)` . Hence, the
following expressions are the same:

`    1. x += y     -     x = x+y`\
`    2. x -= y     -     x = x-y`\
`    3. x *= y     -     x = x*y`\
`    4. x /= y     -     x = x/y`\
`    5. x %= y     -     x = x%y`

The value of the assignment expression is the value of the left operand
after the assignment. Thus, assignments can be chained; e.g. the
expression `a = b = c = 0;` would assign the value zero to all three
variables.

### Comma operator

The operator with the least precedence is the comma operator. The value
of the expression `x, y` will evaluate both `x` and `y`, but provides
the value of `y`.

This operator is useful for including multiple actions in one statement
(e.g. within a for loop conditional).

Here is a small example of the comma operator:

``` c
int i, x;      /* Declares two ints, i and x, in one declaration.
                  Technically, this is not the comma operator. */

/* this loop initializes x and i to 0, then runs the loop */
for (x = 0, i = 0; i <= 6; i++) {
    printf("x = %d, and i = %d\n", x, i);
}
```

## References

fr:Programmation
C/Opérateurs
pl:C/Operatory

[^1]: GCC: \"Optimize common rotate
    constructs\"

[^2]: \"Cleanups in ROTL/ROTR DAG combiner
    code\"
    mentions that this code supports the \"rotate\" instruction in the
    CellSPU

[^3]: \"replace private copy of bit rotation
    routines\"
    \-- recommends including \"bitops.h\" and using its rol32 and ror32
    rather than copy-and-paste into a new program.


# C Programming/Arrays and strings

Arrays in C act to store related data under a single variable name with
an index, also known as a *subscript*. It is easiest to think of an
array as simply a list or ordered grouping for variables of the same
type. As such, arrays often help a programmer organize collections of
data efficiently and intuitively.

Later we will consider the concept of a *pointer*, fundamental to C,
which extends the nature of the array (array can be termed as a constant
pointer). For now, we will consider just their declaration and their
use.

## Arrays

C arrays are declared in the following form:

``` text
type name[number of elements];
```

For example, if we want an array of six integers (or whole numbers), we
write in C:

``` c
int numbers[6];
```

For a six character array called *letters*,

``` c
char letters[6];
```

and so on.

You can also initialize as you declare. Just put the initial elements in
curly brackets separated by commas as the initial value:

``` text
type name[number of elements]={comma-separated values}
```

For example, if we want to initialize an array with six integers, with
`0, 0, 1, 0, 0, 0` as the initial values:

``` c
int point[6]={0,0,1,0,0,0};
```

Though when the array is initialized as in this case, the array
dimension may be omitted, and the array will be automatically sized to
hold the initial data:

``` c
int point[]={0,0,1,0,0,0};
```

This is very useful in that the size of the array can be controlled by
simply adding or removing initializer elements from the definition
without the need to adjust the dimension.

If the dimension is specified, but not all elements in the array are
initialized, the remaining elements will contain a value of 0. This is
very useful, especially when we have very large arrays.

``` c
int numbers[2000]={245};
```

The above example sets the first value of the array to 245, and the rest
to 0.

If we want to access a variable stored in an array, for example with the
above declaration, the following code will store a 1 in the variable `x`

``` c
int x;
x = point[2];
```

Arrays in C are indexed starting at 0, as opposed to starting at 1. The
first element of the array above is `point[0]`. The index to the last
value in the array is the array size minus one. In the example above the
subscripts run from 0 through 5. C does not guarantee bounds checking on
array accesses. The compiler may not complain about the following
(though the best compilers do):

``` c
char y;
int z = 9;
char point[6] = { 1, 2, 3, 4, 5, 6 };
//examples of accessing outside the array. A compile error is not always raised
y = point[15];
y = point[-4];
y = point[z];
```

During program execution, an out of bounds array access does not always
cause a run time error. Your program may happily continue after
retrieving a value from point\[-1\]. To alleviate indexing problems, the
sizeof() expression is commonly used when coding loops that process
arrays.

Many people use a macro that in turn uses sizeof() to find the number of
elements in an array, a macro variously named \"lengthof()\",[^1]
\"MY_ARRAY_SIZE()\" or \"NUM_ELEM()\",[^2]
\"SIZEOF_STATIC_ARRAY()\",[^3] etc.

``` c
int ix;
short anArray[]= { 3, 6, 9, 12, 15 };

for (ix=0; ix< (sizeof(anArray)/sizeof(short)); ++ix) {
  DoSomethingWith("%d", anArray[ix] );
}
```

Notice in the above example, the size of the array was not explicitly
specified. The compiler knows to size it at 5 because of the five values
in the initializer list. Adding an additional value to the list will
cause it to be sized to six, and because of the sizeof expression in the
`for` loop, the code automatically adjusts to this change. Good
programming practice is to declare a variable `<i>`{=html}size
`</i>`{=html}, and store the number of elements in the array in it.

size = sizeof(anArray)/sizeof(short)

C also supports multi dimensional arrays (or, rather, arrays of arrays).
The simplest type is a two dimensional array. This creates a rectangular
array - each row has the same number of columns. To get a char array
with 3 rows and 5 columns we write in C

`char two_d[3][5];`

To access/modify a value in this array we need two subscripts:

``` c
char ch;
ch = two_d[2][4];
```

or

``` c
two_d[0][0] = 'x';
```

Similarly, a multi-dimensional array can be initialized like this:

``` c
int two_d[2][3] = {{ 5, 2, 1 },
                   { 6, 7, 8 }};
```

The number of columns must be explicitly stated; however, the compiler
will find the appropriate amount of rows based on the initializer list.

There are also weird notations possible:

``` c
int a[100];
int i = 0;
if (a[i]==i[a])
{
  printf("Hello world!\n");
}
```

------------------------------------------------------------------------

a\[i\] and i\[a\] refer to the same location. (This is explained later
in the next Chapter.)

## Strings

!String \"Merkkijono\" stored in
memory{width="300"}
C has no string handling facilities built in; consequently, strings are
defined as arrays of characters. C allows a character array to be
represented by a character string rather than a list of characters, with
the null terminating character automatically added to the end. For
example, to store the string \"Merkkijono\", we would write

``` c
char string[11] = "Merkkijono";
```

or

``` c
char string[11] = {'M', 'e', 'r', 'k', 'k', 'i', 'j', 'o', 'n', 'o', '\0'};
```

In the first example, the string will have a null character
automatically appended to the end by the compiler; by convention,
library functions expect strings to be terminated by a null character.
The latter declaration indicates individual elements, and as such the
null terminator needs to be added manually.

Strings do not always have to be linked to an explicit variable. As you
have seen already, a string of characters can be created directly as an
unnamed string that is used directly (as with the printf functions.)

To create an extra long string, you will have to split the string into
multiple sections, by closing the first section with a quote, and
recommencing the string on the next line (also starting and ending in a
quote):

``` c
char string[58] = "This is a very, very long "
                "string that requires two lines.";
```

While strings may also span multiple lines by putting the backslash
character at the end of the line, this method is deprecated.

There is a useful library of string handling routines which you can use
by including another header file.

``` c
#include <string.h>  //new header file
```

This standard string library will allow various tasks to be performed on
strings, and is discussed in the Strings
chapter.

## References

et:Programmeerimiskeel
C/Massiivid
fr:Programmation C/Tableaux
it:C/Vettori e
puntatori/Vettori
pl:C/Tablice
fi:C/Taulukot

[^1]: Pádraig Brady. \"C and C++
    notes\".

[^2]: C Programming/Pointers and
    arrays

[^3]: MINC/Reference/MINC1-volumeio-programmers-reference