> For the complete documentation index, see [llms.txt](https://monasheng.gitbook.io/zerotohero/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://monasheng.gitbook.io/zerotohero/arduino-zero-to-hero/arduino-programming/c-refresher-onramp.md).

# C Refresher/OnRamp

{% embed url="<https://youtu.be/vZcvEgzJI4M>" %}

## Introduction

The below provides a high-level introduction to the `C` programming language, assuming you already know how to code. Only essential functionalities of `C` are provided. For more in-depth information, consider consulting one of the numerous free `C` courses available online.

{% embed url="<https://www.w3schools.com/c/c_intro.php>" %}
Introduction to C is a free, online C course provided by W3 schools.
{% endembed %}

Where possible, the specific Arduino documentation for each `C` functionality is also provided. You should consider reading these linked pages as the provide additional information about the specific implementation of `C` on Arduino boards.

## Comments

In `C`, lines of code preceded with `//` or bounded by `/* ... */` are ignored by the compiler and treated as human-readable comments.

```arduino
// This is a comment

// This is also a comment

/* This too is a comment
and so is
anything enclosed in
this 'block'.
The comment "block" ends here -> */
```

{% embed url="<https://www.arduino.cc/reference/en/language/structure/further-syntax/singlelinecomment/>" %}

{% embed url="<https://www.arduino.cc/reference/en/language/structure/further-syntax/blockcomment/>" %}

## Variable Declaration and Assignment

In `C`, variables must be *declared* before they can be used. A declaration tells the compiler what type of data you plan to store in the variable (and thus, how much memory to put aside for it). One declared, you can then assign a value to a variable using the assignment (`=`) operator.

{% code overflow="wrap" %}

```arduino
// Declare a variable named x to store integer values in
int x;
// Assign the value "2" to x.
x = 2;
```

{% endcode %}

It is also possible to declare and assign in a single command:

{% code overflow="wrap" %}

```arduino
// Declare a variable named x to store integers in, and assign the value "2" to it.
int x = 2;
```

{% endcode %}

{% embed url="<https://www.arduino.cc/reference/en/language/structure/arithmetic-operators/assignment/>" %}

### Variable Data Types

To efficiently utilise storage, it is generally accepted good practice is to use the least-intensive data type you can for an application (i.e. use `int` to store integer values, single-precision `float` to store up to 6-decimal places of precision, etc.

{% embed url="<https://www.arduino.cc/reference/en/language/variables/data-types/int/>" %}

{% embed url="<https://www.arduino.cc/reference/en/language/variables/data-types/float/>" %}

{% embed url="<https://www.arduino.cc/reference/en/language/variables/data-types/double/>" %}

C also has other data types, including string/char, arrays, etc. We won't touch on those here, but the below resource describes these in some detail.

{% embed url="<https://www.tutorialspoint.com/cprogramming/c_data_types.htm>" %}

## Line Termination and Whitespace

Most lines of C code must terminate with a semicolon:

```arduino
// This is a valid declaration, and will compile fine
int x = 2;
// This is not, and will cause an error!
int x = 2
```

## Conditionals

C has provisions for complex conditionals, including `SWITCH/CASE`, but a simple `IF` is usually sufficient most purposes. In C we wrap our conditions in parentheses `()` and the code to be executed in curly braces `{}`:

{% code overflow="wrap" %}

```arduino
  if (tempOutside < 20) {
    // Code in here gets executed if the IF statement is TRUE
    Serial.println("Better bring an umbrella!");
  }
```

{% endcode %}

{% hint style="danger" %}
:zap: **Warning:** While the `IF` structure, bounded by curly braces `{}`, mustn't terminated with a semicolon, any statements within it must!
{% endhint %}

{% embed url="<https://www.arduino.cc/reference/en/language/structure/control-structure/if/>" %}

Ordinarily, `IF` structures are entirely bypassed if the condition in round brackets `()` is not met. To ensure orthogonality, you might consider using an `IF/ELSE`:

{% code overflow="wrap" %}

```arduino
  if (tempOutside < 20) {
      // Code in here gets executed if the first IF statement is TRUE
      Serial.println("Better bring an umbrella!");
  } else if (tempOutside > 30) {
      // Code in here is executed if the first IF statement is FALSE & second is TRUE
      Serial.println("Better bring sunscreen!");
  }
```

{% endcode %}

{% hint style="info" %}
:man\_mage: **Important:** Unlike Python, indenting is not required for compilation to work as `C` ignores whitespace, but indenting within `IF` structures is still considered good practice for human readability!
{% endhint %}

{% embed url="<https://www.arduino.cc/reference/en/language/structure/control-structure/else/>" %}

## Loops

C has provision for several types of loop for performing iterative (over and over again) calculations.

### `for()` Loops

`for()` loops are good if you need to do something a fixed number of times.

{% code overflow="wrap" %}

```arduino
// Loop 10 times.
// Note that here, i starts at i = 0 and is incremented by 1 each loop iteration (i++). The strict inequality on the termination condition (i<10) means the loop will run exactly 10 times.
for (int i = 0; i < 10; i++) {
  Serial.print("Value of i: "); Serial.println(i);
  // Wait for a second before the next iteration
  delay(1000); 
}
```

{% endcode %}

{% embed url="<https://www.arduino.cc/reference/en/language/structure/control-structure/for/>" %}

### `while()` Loops

`while()` loops will run indefinitely, until a set condition is met.

```arduino
int i = 0; // Initialize the variable

// Loop to increment and print the variable
while (i < 10) {
  Serial.print("Value of i: ");
  Serial.println(i);
  // Increment i
  i++; 
  // Wait for a second before the next iteration
  delay(1000); 
}
```

Because they are unbounded, `while()` loops can run *forever*. This can be very useful and dangerous - use these with care!&#x20;

{% embed url="<https://www.arduino.cc/reference/en/language/structure/control-structure/while/>" %}

## Constant Definitions

At the top of your code, you can hard-define constant values to use throughout. The `#define` method provides this functionality, with syntax as follows:

```arduino
#define CONSTANT_NAME value
```

Note that:

1. This line must be unterminated - i.e. no `;` is used,
2. This line is a defintion, rather than a variable assignment, and thus no `=` is used,
3. When naming constants, it is customary to use underscores in place of spaces, and `ALL CAPS`, and,
4. constants defined this way are constrained to remain the same/cannot be changed throughout the sketch. They are constants, after all, *not* variables!

```arduino
#define BLINK_DELAY_MS 500 // Define the delay time in milliseconds

void setup() {
    pinMode(LED_BUILTIN, OUTPUT); // Set the LED pin as an output
}

void loop() {
  digitalWrite(LED_BUILTIN, HIGH); // Turn the LED on
  delay(BLINK_DELAY_MS); // Wait for the specified delay time
  digitalWrite(LED_BUILTIN, LOW); // Turn the LED off
  delay(BLINK_DELAY_MS); // Wait for the specified delay time
}
```

{% embed url="<https://www.arduino.cc/reference/en/language/structure/further-syntax/define/>" %}

## Off-the-shelf libraries

You need not write every piece of code for yourself. C allows you to include libraries that others have written via the `#include` method. The syntax is as follows:

```arduino
#include <LibraryFile.h>
#include "LocalFile.h"
```

Where:

* `LibraryFile.h` is a library installed to your computer (i.e. via the [Arduino IDE](/zerotohero/arduino-zero-to-hero/arduino-ide.md#library-manager) in the [Arduino IDE](/zerotohero/arduino-zero-to-hero/arduino-ide.md)), or,
* `LocalFile.h` is a library that you have downloaded (e.g. from GitHub), or have written yourself, and is stored in the same directory as your main code/sketch.

Note that:

1. `#include` calls must be unterminated, and thus no `;` is used,
2. Angle brackets `<>` are used to include IDE-installed libraries, and quotation marks `""` are used to include local files/libraries,
3. `#include` calls must be made outside of any function, usually at the very start of your code.

```arduino
// Preamble
#include <math.h> // Include the math library (for the square root function)

// Setup
void setup() {
  Serial.begin(9600); // Initialize serial communication
}

void loop() {
  Serial.print("Square root of 4 = "); Serial.println(sqrt(4));
  delay(1000); // Delay for 1 second before loop runs again
}
```

{% embed url="<https://www.arduino.cc/reference/en/language/structure/further-syntax/include/>" %}

## Functions

C allows you to write your own functions. These are helpful if you have some low-level operation that you need to apply to different inputs over and over again. They are also quite useful for readability, testability, and troubleshooting - see [Clean Code](/zerotohero/arduino-zero-to-hero/core-skills/clean-code.md).

C Functions have two key 'ingredients':

1. A [#function-definition](#function-definition "mention")*,* where the function inputs/outputs and structure is defined, and,
2. A [#function-call](#function-call "mention"), where the function is used in the main body of the code.

#### Function Definition

Function definitions are usually placed at the *bottom* of your script/sketch/program, after all other code. They include:

1. The *type* of the function output (e.g. int for an integer output, float for a floating point, or void for no output),
2. The name of the function,
3. A list of function inputs, with their associated expected type, and,
4. The function itself.

Consider the following example function definition:

```arduino
int myFunction(int a, int b) {
int c = (2 * a) + b;
  return c;
}
```

Here, the function:

1. is named `myFunction,`
2. takes two inputs, which it internally refers to as `a` and `b`,
3. returns an output of type `int`, an integer,
4. works by creating an internal variable that it calls `c` ,  storing a value equal to $$2\times a + b$$ in this variable, and returning it as the integer function output.

#### Function Call

In the main body of your code, you can use self-developed functions by *calling* them as follows:

<pre class="language-arduino"><code class="lang-arduino">// Call myFunction to compute 2*3+4
<strong>c = myFunction(2,4);
</strong></code></pre>

Interestingly, functions maintain a different variable memory space than the rest of your code. This means that they don't know the names of the variables they take as input. Instead, they rely on the order in which inputs are given to map them to their internal variable names.

For instance,

<pre class="language-arduino" data-overflow="wrap"><code class="lang-arduino">// Create some variables
x = 2;
y = 3;
// Call myFunction to compute 2*x+y
<strong>z = myFunction(x,y);
</strong></code></pre>

returns $$z=(2\times2)+3 = 7$$ as you might expect, but

<pre class="language-arduino"><code class="lang-arduino">// Create some variables
x = 2;
y = 3;
// Call myFunction to compute 2*y+x
<strong>z = myFunction(y,x);
</strong></code></pre>

returns $$c=(2\times3)+2=8$$. This is because myFunction internally maps the first input to `a` and the second to `b.`

1. Here, the function call takes variables as input that have *different names* than what were used in the function definition. This is OK! The function knows which variable to use as `a` and which to use as `b` based on their *order* in the call - in this case `x=2` is used as `a` and `y=3` is used as `b`.
2. You need not only use variables as input, you can also hard-code values, e.g. `z = myFunction(2,3);`, or use the same value: `z = myFunction(x,x);`.

{% embed url="<https://docs.arduino.cc/learn/programming/functions/>" %}
