# Deciphering Strange Arduino Code

## Overview

![An example of some truly twisted code in Adafruit_NeoPixel_ZeroDMA](https://cdn-learn.adafruit.com/assets/assets/000/114/026/medium800/microcontrollers_weird-code-banner.png?1660017679)

As one works their way up from the Arduino “blink” sketch into increasingly sophisticated projects, part of that process entails more exposure to others’ code…open source projects, libraries that encapsulate particular functionality and so forth. Such code originates from folks of all backgrounds and skill levels, and you will invariably encounter some head-scratching moments. **Not necessarily _bad_ code, but _weird._**

This guide explains a few lesser-seen elements of C syntax. **“The Arduino language” is really C++, which is basically C with added flavor crystals.** [C was developed back in the early 1970s](https://en.wikipedia.org/wiki/C_(programming_language)) and has become one of the most widely-used programming languages. With such a long and diverse history, you’re bound to find some odd creatures under the floorboards.

There are a couple of reasons this might be of interest:

- To expand one’s own C (and C++, and thus Arduino) programming knowledge; **maybe there’s valuable tips here to _use._**
- To write code that’s friendlier to newcomers; **maybe these are things to _avoid._** If it confused _you,_ it may confuse _others,_ and that’s not ideal for teaching!

## How Does This Happen?

There are a number of ways that _strange code_ might manifest…

- **Familiarity** with a programming language can lead to **_contractions,_** just as with spoken languages. In English, “is not” and “can not” become “isn’t” and “can’t.” C and most other programming languages have some shorthands that aren’t always obvious to new learners.
- With C’s long history, some of today’s projects are written by folks with _decades_ of experience…who may have habits ingrained when disk and screen real estate were **highly constrained,** and who’s natural “flow state” is to always **pack _more code_ in _fewer characters._**
- Again with long-time programmers…even into the late 1990s, one was _fortunate_ to get a free (and rudimentary) C compiler with a $30,000 UNIX workstation. Commercial optimizing compilers could add&nbsp;_thousands more._ So there was a tendency to **attempt optimizations manually.** Some of the code in today’s projects is carried over from posterity. Some is just written weird out of habit.
- Programmers have a wicked sense of humor. _ **Obfuscation** —_intentionally writing to be difficult to understand—can be _funny,_ and there’s even [contests for such things](https://www.ioccc.org). **You _don’t_ want this in teachable code,** but occasionally one might drop a punchline for other veteran programmers. On rare occasion obfuscation is done with intent to be “31337” or to conceal trade secrets…but that’s petty, please don’t.
- **Maybe I wrote it.** If reading the source code to some Arduino library and it’s like “What were they thinking?”, check for my name on it. With the exception of malicious obfuscation, I’m guilty of _all_ of these. Sorry about that.

**This is _not_ a comprehensive C programming guide; it only covers a few specific sticky topics that have raised questions in the [Adafruit Forums](https://forums.adafruit.com).&nbsp;For well-rounded learning, there are&nbsp;many classic books on the subject, or just by following along with Arduino tutorials.**

Nothing discussed here is broken or illegal. It’s all part of the formal C lexicon, just less-used…like the English language words “brambles” or “lugubrious.”

# Deciphering Strange Arduino Code

## Funny “for” Loops

C provides several ways to _iterate—_repeat a sequence of steps. Chief among them are `while`, `do-while` and `for` loops. Arduino adds the `loop()` function for the main body of a program; canonically C does not provide that one on its own.

## Background
A `while` loop resembles the following:

```auto
// Initialization can go here
while (condition) {
  // Body of loop
}
```

“`condition`” is a placeholder—this gets replaced with some true/false statement; perhaps comparing a variable against a number, or checking the return status of another function. As long as the statement evaluates as true, then the code in the body of the loop is executed again and again.

Initializing one or more variables before the loop is common, but not required of all programs.

A _`do-while`_ loop moves the test condition to the _end:_

```auto
// Initialization can go here
do {
  // Body of loop
} while (condition);
```

“`condition`”—the true/false statement—is evaluated _after_ the body of the loop. So the loop always executes at least once.

Some logic just works better one way or the other.

A _`for`_ loop is sort of a **contraction** of the `while` loop:

```auto
for (initialization; condition; operation) {
  // Body of loop
}
```

“`initialization`” is any code that sets up the loop…for example, it’s very common to set up a counter variable here. 92% of `for` loops start with an “`i=0`” initialization _(programmer humor, not a true statistic, but it’s quite common)._

“`condition`” is just like the `while` loop—a testable true/false statement, evaluated _before_ each iteration of the loop. Very often tests a counter against some limit, e.g. `i<10`.

“`operation`” is a simple statement that’s performed _after_ each iteration of the loop body. Very often used to increment a counter, e.g. `i++`;

So&nbsp;_three lines_ of code before now all fit into _one._ It’s a nice shorthand.

 **FUN FACT:** conditional statements can _also_ test integers for non-zero-ness. A variable with value&nbsp;`0` is equivalent to `false`. `1`, `42`, `-303` or _any other non-zero integers_ are `true`.&nbsp;Okay, maybe not _fun,_ but it’s a _fact._

## `for` Shenanigans
Not often seen, hence occasional confusion, **but any of the parts of a `for` loop are optional;** they can just be omitted when not needed, as long as the other remaining syntax (semicolons, etc.) is observed. These are all valid `for` loops:

```auto
for (; condition; operation) {
  // Body of loop
}

for (initialization; ; operation) {
  // Body of loop
}

for (initialization; condition; ) {
  // Body of loop
}

for (initialization; condition; operation);
// I ain't got no body
```

`while` loops can also omit the body and just end with a semicolon, but `do-while` loops _always_ have the braces.

Recent C++ compilers allow declaring temporary variables&nbsp;_right inside the initialization of a `for` loop._&nbsp;This wasn’t always the case, so you don’t see it in older code.&nbsp;The “scope” of such variables is limited to the body of the loop (i.e. can’t be referenced after the loop).

One can also use a _comma separator_&nbsp;to pack more stuff into a line, e.g.

```auto
for (int a=0, b=1, c=2; a&lt;10; a+=1, b+=2, c*=3) {
	Serial.printf("%d %d %d\n", a, b, c);
}
```

_(Note: `Serial.printf()` is typically present only for 32-bit microcontrollers in Arduino. With Arduino UNO and other 8-bit devices, one must `Serial.print()`&nbsp;each value separately.)_

## Old Habits Die Hard

It’s very common in C/C++/Arduino to structure an _infinite loop_ (that is, repeats until power is cut) like the following:

```auto
while (1) { // Always true; repeats forever
  // Body of loop
}
```

Occasionally there’s no body, if a program encounters an error and needs to “hang” because it can’t safely continue. The line just ends with a semicolon.

In the introduction,&nbsp;_aged programmers,_ _poor-quality compilers_&nbsp;and _code I wrote_ were all mentioned. Combined with a `for` loop’s aforementioned optional elements, this yields a valid but little-seen infinite loop syntax:

```auto
for (;;) {
  // Body of loop
}
```

I developed this habit because _one particular compiler_ on _one particular system_&nbsp;decades ago&nbsp;would generate machine code that actually _evaluates the truth of a `while(1)` statement_ every time, instead of seeing the obvious infinite loop and simply jumping without evaluating. The empty `for` was more efficient.

**_No_ compiler nowadays is that stupid,** they will always do the right thing.&nbsp;But in the time and circumstances, it made programs a few cycles faster and a few bytes smaller.

I only stick with `for(;;)` because it _looks cool_ and I get to _tell Big Iron Stories…_but it’s preferable for _teachable code_ to use `while(1)` because that’s _universally understood_ today as “infinite loop.”

# Deciphering Strange Arduino Code

## What the ?

It’s fitting that the one thing&nbsp;that seems to generate the most C code questions is a single character: **?** — the question mark.

This is C’s **_ternary operator._** Or as I like to call it, the Altoids operator, as it packs a _lot_ of flavor into a tiny package.

Consider the following code:

```auto
if (condition) {
	a = 42;
} else {
    a = 17;
}
```

The ternary operator provides a shorthand for this construct,&nbsp;packing a conditional test, if/else and assignment into a _single line:_

```auto
a = condition ? 42 : 17;
```

_“`condition`,” again, is a placeholder. This is not real code. An actual program would have a meaningful thing to test there._

If the condition evaluates as `true`, the first value (left of the colon) is used. If false, the second value (after colon) is used.

While this if/else/assign pattern doesn’t come up a whole lot, it’s used _just enough_ that you can easily imagine how veteran programmers, who may have grown up on a single fixed 80x25 character screen, would _love_ something so nutrient-dense.

The downside is that, on its own, it’s kind of&nbsp;_nonsensical._&nbsp;Other C keywords like `do`, `while`, `if` and `else` provide at least _some vague indication of what they do._ But `?` is like&nbsp;they’d used up every last character on the keyboard for something else and it came down to this. I guess you could say it’s **a condition phrased like a question.**

It’s not just for A/B assignment. You can wrap this up in a conditional statement (e.g. `while`), or put function calls on one or both sides of the colon:

```auto
while (value ? func1() : func2()) {
  // Body of loop
}
```

Much as I appreciate its density, it’s only right to **avoid** inflicting this on those just starting out, that would be _mean._ You’ll never see this in NeoPixel _strandtest._

But to seasoned coders, it’s expressing a complex idea in a small space.&nbsp;Deep down inside libraries I’ll use it all over the place, but&nbsp;that’s basically the code equivalent of at-home in a bathrobe.

And for projects aimed at _intermediate_ coders?&nbsp;Love to put one or two in there just to _make_ them ask questions.

# Deciphering Strange Arduino Code

## goto

Many folks aren’t even aware that C/C++/Arduino _has_ a `goto` command.&nbsp;It is so reviled,&nbsp;tutorials often skip over this.

`goto` continues program execution at a different place within a function.

The reason it’s considered so distasteful is that overdependence quickly leads to _ **spaghetti code**._ Unlike the braces and conditionals that visually represent the structure and flow of code, `goto`&nbsp;throws that all out the window…it just _goes_ places and is hard to follow.

The canonical use case for `goto` is breaking out of _nested loops:_

```auto
for (int a=0; a&lt;10; a++) {
  for (int b=0; b&lt;10; b++) {
    if (condition) goto linguini;
  }
}
linguini:
// Code continues here
```

The nested inner part of the loops will execute 100 times, unless some condition arises. Well okay, that’s _one way_ out of the situation.

Keep in mind that anything that can be written _with_ `goto` can (maybe _should_) be written _without._&nbsp;One could add conditional tests to the `a` and `b` loops…at the expense of a few cycles.&nbsp;One could put the nested loops inside their own function and use `return` instead of `goto`.…at the expense of a few-bytes-larger program. Always some small expense.

Potentially, infrequently, `goto` could get you out of a bind, but other programmers will look upon you like the cat threw up on the rug.&nbsp;Extremely, _extremely_ infrequently, I might use _one,_ preceded by _a whole apologetic paragraph in comments explaining the justification for its use._ But usually I’ll avoid it and go through the extra hoops just to steer away from the whole tired argument.

# Deciphering Strange Arduino Code

## Peripheral Registers

Sometimes in an Arduino project, especially projects tied to hardware, you’ll see a line accessing a variable that _isn’t even declared anywhere in the code._

```auto
TCCR5A = 42;
```

Like…who is `TCCR5A`?&nbsp;Nobody’s declared it anywhere, yet the program compiles fine (for certain boards).&nbsp;Meanwhile, I miss _one_ variable declaration in my code and the compiler throws absolute fits!&nbsp;What’s going on?

A microcontroller doesn’t just run programs, it also _talks to hardware_&nbsp;like buttons, LEDs, weather sensors and small displays. So alongside the CPU, which _does_ run programs, there sit additional silicon circuits called **_peripherals_** to assist with those other tasks.

The CPU needs a way to exchange data with those peripherals…read a button, or turn on an LED. To do this, peripherals are _ **memory-mapped**._&nbsp;They _appear to the CPU_ just like part of main memory, like variables or arrays, but behind the scenes are actually _connected to these peripheral functions_ and not RAM at all.

So, somewhere off in a header file that the Arduino compiler includes automatically, all of those peripheral registers are declared and assigned absolute addresses as if in memory. If you read from or write to those “variables,” you’re actually talking directly to the hardware!

`TCCR5A` in this case is a timer control register, specific to some AVR microcontrollers…the ATmega1280 and ATmega2560 seen on Arduino Mega boards. This register’s used to set up timekeeping or PWM on certain pins.

And that’s the thing…these registers are _extremely_ device-specific; you won’t find `TCCR5A` on other chips. There may be _some_ overlap within a few related chips of a family, but by and large this does not work when moving code between unrelated devices. If you see Arduino code doing this,&nbsp;it’s really getting into some low-level sorcery.

We can only scratch the surface of the topic here,&nbsp;just wanting to explain what these mystery variables are about.&nbsp;[This guide about the TiCoServo library](https://learn.adafruit.com/neopixels-and-servos/introducing-avr-peripherals) explains a bit further.&nbsp;If you get deep into the hardware side of things, understanding peripherals and&nbsp;navigating chip datasheets becomes a vital skill.

# Deciphering Strange Arduino Code

## stdint

Any C or Arduino tutorial quickly gets into integer _types,_ where there’s a tradeoff between the memory required for a variable, and the range of values it can hold:

```auto
char a;
int b;
long c;
```

But soon you might encounter code that looks like _this,_ perhaps with no explanation:

```auto
int8_t a;
int16_t b;
int32_t c;
```

A funny thing about C is that those first three types—`char`, `int`, `long`—_do not have a canonical size_ that’s true among all situations! It’s totally implementation-dependent…

For example, on the Arduino UNO and similar, `int` (and cousin `unsigned int`) are 16-bit values…two bytes in RAM…with a range from −32,768 to 32,767 (or 0 to 65,535 for the unsigned variant).

But switch to most any 32-bit microcontroller and now those&nbsp;`int`s are _32-bit_ values…four bytes in RAM, with a much larger range. Same type names, but different utilization. **Sometimes, code falls over due to this change.**

The **stdint.h** header file…included automatically by the Arduino compiler…declares a set of known-sized integer types which can be relied on.

`int8_t` is _always, by definition_ an 8-bit signed value (−128 to +127), `uint8_t` is 8 bits unsigned (0 to 255). One byte in RAM.

`int16_t` is _always, by definition_ an 16-bit signed value (−32,768 to +32,767), `uint16_t` is 16 bits unsigned (0 to 65,535). Two bytes in RAM.

`int32_t` is _always, by definition_ a 32-bit signed value (−2,147,483,648 to +2,147,483,647), `uint32_t` is 32 bits unsigned (0 to 4,294,967,295). Four bytes in RAM.

If you get into programming outside the Arduino environment, these types are _not_ automatically declared, and one must explicitly:

```auto
#include &lt;stdint.h&gt;
```

# Deciphering Strange Arduino Code

## Octal Literals

Do programming for any length of time and you’ll&nbsp;soon learn about different _number bases,_&nbsp;such as _binary_ or _hexadecimal._&nbsp;It’s especially common with graphics or peripherals…these different notations relate numbers more naturally to the microcontroller’s internal representation.

```auto
int a = 0b00101010; // Binary representation of 42
int b = 0x2A;       // Hexadecimal representation of 42
```

The topic is well covered in existing programming tutorials so **this guide won’t go into detail** ([here’s Wikipedia’s entry on _radix_](https://en.wikipedia.org/wiki/Radix)), but I must _specifically_ warn about **_octal_** notation, which occasionally trips folks up…

Octal is _base 8_ notation…three bits per digit, or values from 0 to 7.&nbsp;Notice how the binary and hexadecimal examples above have `0b` or `0x` at the start? Octal just has a `0`.

What occasionally happens is that folks will “zero pad” regular decimal values to make them fill out space nicely in a table, not realizing that _they’re actually mixing in octal numbers with totally different values,_&nbsp;or will use digits _beyond the valid octal range_ (e.g. `089`), then can’t figure why the program fails. This is&nbsp;_strange_ in that the other representations don’t mind being zero-padded…

```auto
int table1[] = {
  0b00000000, // Binary representation of 0
  0b00101010, // Binary rep. of 42 (harmless leading zeros!)
  0b11111111, // Binary rep. of 255
};

int table2[] = {
  0x0000, // Hexadecimal representation of 0
  0x002A, // Hex rep. of 42 (harmless leading zeros!)
  0x00FF, // Hex rep. of 255
};

int table3[] = {
  000, // Octal representation of 0
  042, // *** Octal rep. of 34! Danger! Danger! ***
  089, // *** Invalid octal value! Danger! ***
  255, // Decimal rep of 255
};
```

Use of octal notation is _super rare_ nowadays, but the formal C specification _requires_ its inclusion for compatibility. If you encounter code using this&nbsp;_at all_ it’s probably been ported from truly ancient platforms.&nbsp;Because…this might blow your mind…_bytes weren’t always 8 bits!_

https://www.youtube.com/watch?v=AP5DvumwiVM

What blows my mind even more is that&nbsp;the _very first_ stored-program computer _ever—_the [Manchester Baby](https://en.wikipedia.org/wiki/Manchester_Baby)—had a “modern” 32-bit word length. Its immediate successor…_and a majority of systems for the next two decades…_took other directions that favored octal numbers before mainstreaming back to 32 bits in the late 1960s.

This fact has nothing to do with strange C code…C didn’t even _exist_ yet…I just think it’s _so neat!_

# Deciphering Strange Arduino Code

## Compare vs Assign

Something that _will_ bite you in the hiney is C’s reliance on single vs. doubled-up characters for certain _related_ but not _congruent_ functionality.

It’s not _if,_ but _when_ you’ll lose hours or even days hunting an “inexplicable” bug…

```auto
if (a = 42) {
  // Do the thing
}
```

You _know_ this by now, but for posterior: a _single equals_&nbsp;(`=`) is an assignment, _double equals_&nbsp;(`==`) is a comparison. In vs. out. The code above is assigning where it should be comparing…and because the result is non-zero, always evaluates as&nbsp;`true`.

This happens _all the time,_ and will happen _forever._

Complexifying matters, and on theme with this guide’s focus, seasoned coders sometimes economize on space by _intentionally_ putting an assignment inside an `if` (or `while`, etc.) statement…

```auto
if ((value = func())) {
  // Do the thing
}
```

This calls `func()`, assigns the returned result to `value`, then _does the thing_ if the result was non-zero. This is actually _normal and valid C syntax,_&nbsp;and at most it’s _optional_ but _recommended_ to have double parenthesis (as above) as if to tell others, “I meant to do that.”

![Pee Wee Herman](https://cdn-learn.adafruit.com/assets/assets/000/114/024/medium640/microcontrollers_meant-to-do-that.jpg?1660017703)

_Assignment_ sometimes gets paired up with another, different character (or two) to perform an _operation_ on a variable in one compact step, for example…

```auto
x += 3;  // Add 3 to x, assign result back to x; equiv. to x = x + 3
x -= 3;  // Subtract 3 from x, assign back to x; equiv to x = x - 3
x *= 3;  // Multiply x by 3, assign result back to x; equiv x = x * 3
x /= 3;  // Divide x by 3, and so forth...
x %= 3;  // x modulo 3, "
x &amp;= 3;  // Bitwise AND of x and 3, "
x |= 3;  // Bitwise OR of x and 3, "
x ^= 3;  // Bitwise XOR of x and 3, "
x &lt;&lt;= 3; // Shift x left 3 bits, assign result back to x
x &gt;&gt;= 3; // Shift x right 3 bits, assign result back to x
```

But a few of these, syntactically similar, are actually _comparisons…_

```auto
if (x != 3) // If x does not equal 3...
if (x &lt;= 3) // If x is less than or equal to 3...
if (x &gt;= 3) // If x is greater than or equal to 3...
```

Of these, the bitwise shifts vs greater/less-than comparisons are most likely to cause misunderstandings.

# Deciphering Strange Arduino Code

## Logical vs Bitwise

Another single-vs-double character&nbsp;situation occurs between&nbsp;_logical operators_ (evaluating the `true`/`false` condition of a statement) and _bitwise operators_ (applying mathematical combinations to numbers).

```auto
if (flag1 || flag2) {        // This is a LOGICAL OR operator
  result = value1 | value2;  // This is a BITWISE OR operator
}
```

The compiler will rarely complain if you mix these up, because&nbsp;integers can be evaluated as `true` (non-zero) or `false` (zero).

`||` is the **logical OR** operator, true if the operand on _either side_ is true.

`&&` is the **logical AND** operator, true only if operands on _both sides_ are true.

`!` is a **logical NOT** , which _negates_ the operand following it. `true` becomes `false` and vice versa. Notice this one’s only a _single character._

 **Bitwise, meanwhile…**

`|`, `&`, `^` and `~` are bitwise **OR** , **AND** , **XOR** and **NOT** operators. `<<` and `>>` are bitwise **shift** operations,&nbsp;ensuring that we can’t make a single, all-encompassing “one versus two characters” differentiation.&nbsp;We’ll not go into detail of the operations themselves, [already well covered elsewhere](https://en.wikipedia.org/wiki/Bitwise_operation).&nbsp;As mentioned on the prior page, any of these can be paired up with an assignment (`=`) as a shorthand operation.

Bitwise shifts have the interesting property of dividing or multiplying integers by powers of two…

```auto
a = b &lt;&lt; 1; // Multiply by 2
a = b &lt;&lt; 2; // Multiply by 4
a = b &lt;&lt; 3; // Multiply by 8, etc...
a = b &gt;&gt; 1; // Divide by 2
a = b &gt;&gt; 2; // Divide by 4
a = b &gt;&gt; 3; // Divide by 8, etc...
```

Old-school code often has a lot of bitwise shifts because multiply and divide were relatively costly operations at the time. But modern compilers spot this opportunity and perform such optimizations automatically if beneficial, even at “low” settings.&nbsp;So…if you need to divide a number by 8, _just divide by 8,_ it reads better_.&nbsp;_In other situations bit-shifts are still very appropriate…in graphics for instance, conceptually it may be more readable&nbsp;to shift pixels left or right by a number of bits. All depends on the task and the idea you want to convey.

# Deciphering Strange Arduino Code

## Pointers

_Pointers_ are an integral part of the C language and this won’t go into any depth, but to mention a bit of strange syntax…

Any variable, array or function in C takes up some amount of memory. Code can request a _pointer_ to the start of that memory (“address of”) with the ampersand (`&`) operator. And a variable that is itself a pointer to something else is declared with an asterisk (`*`) operator:

```cpp
char a[100];  // 100 bytes
char *b = &amp;a; // b is a pointer to start of a[] array
```

That’s simple enough. Where it gets strange is that _pointers-to-pointers_ exist:

```auto
char **c = &amp;b;  // Pointer to b variable, which is itself a pointer
char ***d = &amp;c; // Pointer to c variable, itself a pointer-to-pointer
```

_It’s pointers all the way down!_&nbsp;In practical use, I don’t recall ever seeing more than `**` pointers-to-pointers (also sometimes called a _vector_).&nbsp;It’s all a bit obscure, but perfectly valid…one might pass a pointer-to-pointer to a buffer to a library function that may then reallocate it, changing the pointed-to pointer’s value.&nbsp;Don’t be alarmed when you reach that.

## Arrow Operator

_Classes_ in C++ (and _structures_ in both C and C++) are a way of grouping related variables into a single encapsulating&nbsp;_thing._ Classes can also contain functions in addition to variables…but let’s look at a struct first, because it’s simpler:

```auto
struct {
  int month;
  int day;
  int year;
} apple = { 4, 1, 1976 };

Serial.println(apple.year); // Prints "1976"
```

Written this way, memory for the structure called “apple” is allocated at compile time, when it’s being declared, because its contents are a known thing initialized from constant values (April 1st, 1976). To access variables within that structure, a period (“.”) is normally used.

Sometimes a program _doesn’t know ahead of time_ what’s going into a structure or class, or whether it’s even going to be used at all. Such code might allocate the struct or class _dynamically,_ using malloc() (for C) or new (for C++). Consider this code that creates two Adafruit\_NeoPixel objects…one a static declaration, the other dynamic:

```auto
Adafruit_NeoPixel pixels1(42, 5, NEO_GRB);
Adafruit_NeoPixel *pixels2 = new Adafruit_NeoPixel(42, 6, NEO_GRB);
```

Most NeoPixel code is written like the first line. Everything about the NeoPixel strip is known ahead of time…how many pixels there are, what pin it’s connected to, and the color format used.

When it comes time to set a pixel’s color or update the strip, those functions are called with the object name, a period, and the function name:

```cpp
pixels1.setPixelColor(0, 255, 0, 0); // Set first pixel red
pixels1.show();                      // Update strip
```

Trying to do the same with the “pixels2” object would generate errors though, because that object was allocated dynamically…it’s an object _pointer._ Such items require a slightly different syntax:

```cpp
pixels2-&gt;setPixelColor(0, 0, 0, 255); // Set first pixel blue
pixels2-&gt;show();                      // Update strip
```

Since pixels2 is really a _pointer_ to an object, not an object itself, the right arrow “points” to where the object was actually allocated.

Why would anyone do this? Well…in the NeoPixel case…suppose you’re producing a _lot_ of something, in multiple configurations. A toy with 10 pixels than animate in one pattern, and a different toy with 20 pixels in another pattern…but you don’t know ahead of time _how many of each_ you’ll be producing.&nbsp;With the static declaration, if you program the wrong number of boards for each design, some will require re-programming with the correct code. With the dynamic declaration…there might be a switch or jumper that’s set during assembly to select which toy this is going inside…and _every_ board can then be programmed with the _same code_ (which checks the jumper and adapts accordingly), no do-overs needed.

# Deciphering Strange Arduino Code

## Pre/Post Increment/Decrement

Again, little to add here because _pre-_ and _post-_ _increment_ and _decrement_ are simply features of the language. But there’s a funny thing you’ll sometimes see in old-school code.

The rules of these operations are pretty straightforward…

```auto
a = ++b; // Add 1 to value of b, assign back to b, also assign to a
a = --b; // Subtract 1 from value of b, assign back to b, also to a
a = b++; // Assign value of b to a, then add 1 and assign back to b
a = b--; // Assign value of b to a, subtract 1 and assign back to b
```

You’ll see these with pointers and counters a lot, often with the “`a=`” part left off, just performing operations on a single variable. Often the third element of a `for` loop, e.g. `i++`.

Python doesn’t have these operators, preferring `a += 1` or `a -= 1` instead,&nbsp;so they’re a _little_ strange if just coming into C from that language.

Most modern CPUs support all of these operations down at the instruction level; you often get any of these increments or decrements “free” as part of another operation. That wasn’t always true though. If I recall correctly, I think the Motorola 68000 (maybe others) only had pre-decrement and post-increment, and the other combinations required extra cycles as they’re performed “manually.” That chip’s _DBRA_ opcode (decrement and branch if not zero) was particularly efficient for loops.

So…in old code, or even in modern code written by folks with habits ingrained in that era…you may see programmers prostrating themselves to structure program flow into a `do-while` loop (decrementing and testing against zero at the end)…trying to optimize the code manually, because compilers _sucked…_rather than a simpler, more readable (and likely just as efficient now) implementation.

I still do this all the time, but mostly for nostalgia’s sake.

# Deciphering Strange Arduino Code

## Spaces, Tabs and Braces

> “Never attempt to teach a pig to sing; it wastes your time and annoys the pig.”
> 
> – Robert Heinlein

This is **not actually about strange code,** just some productive advice…

As you interact with more of other people’s code,&nbsp;you’ll find everyone has a distinct style. Not just in the flow of logic, or the names of functions and variables,&nbsp;but simply details of _layout._

As long as you always pair up the curly braces and end every statement with a semicolon, C is otherwise nonjudgmental about what goes where. This contrasts with others like Python, which can be strict about consistent indentation, and also has a _whole culture_ of favored coding practices.

These two versions of a C function are roughly equivalent:

```auto
void do_if_odd(uint16_t x) { if(x &amp; 1) do_the_thing(); }

void do_if_odd(unsigned short x)
{
    if (x % 2)
    {
        do_the_thing();
	}
}
```

One is packed tightly like a suitcase, the other spread out like an Apple store. One uses a bitwise AND to check for oddness, the other a modulo operator…but _same result._ The only functional difference is an obscure one:&nbsp;there _might_ be rare platforms where `uint16_t`&nbsp;and&nbsp;`unsigned short`&nbsp;are different sizes. “Readable” is largely in the eye of the beholder; some will grasp program flow better when more is visible on screen,&nbsp;but generally the airy code will be kinder on newcomers.&nbsp;There are countless middle-grounds as well.

 **C Programmers sometimes get into _heated debates_ about The Only Good And Proper Way To Structure Code™.** Should indentation be performed with spaces or with tabs? Should the curly braces starting code blocks appear on their own line, or with the prior statement? Is _goto_ in fact irredeemably evil?

Everyone has preferences. That’s healthy and fine! I get _such_ a thrill when lining up comments in adjacent lines of code. But these are _subjective_ things, you will always find dissenters.

If you’re **contributing to an open source project** , or are part of a **team:** the **_winningest_ strategy I’ve observed of top programmers** —or maybe they’re just _extremely jaded_ programmers—is **&nbsp;_don’t go there._** &nbsp;The _correct_ answer is: _there is no One Answer™._ Instead, within the scope of a project, **adopt the conventions of the project lead, or a mutually agreed-upon style guide.**

**Stay flexible.** Do what you enjoy in _your own_ code, but in _collaborative_ code, the most prolific are _doing the work,_ not arguing over spaces or curly braces, or GIF vs JIF, or pineapple on pizza or tails on werewolves. Take the group conventions to heart and then do the work. Fix that bug. Add that feature. Stop reformatting code like you’re rearranging deck chairs and&nbsp; **_Do. The. Work._**

In Adafruit libraries we’ve [adopted the practices](https://learn.adafruit.com/the-well-automated-arduino-library) of using **clang-format** &nbsp;for consistently formatting C/C++ code (with default settings, nothing special),&nbsp;and **doxygen** for API documentation.&nbsp;If new code is written _close_ to those conventions, it’s minimally disruptive to then filter it through those tools.

I’m _quite certain_ that _not a single person here_ 100% _agrees_ with these tools’ formatting conventions…but it’s always at least _adequate, consistent,_ and avoids _religious&nbsp;debates._&nbsp;No time wasted, no pigs annoyed!


## Featured Products

### Adafruit METRO 328 Fully Assembled - Arduino IDE compatible

[Adafruit METRO 328 Fully Assembled - Arduino IDE compatible](https://www.adafruit.com/product/50)
We sure love the ATmega328 here at Adafruit, and we use them&nbsp;_a lot_&nbsp;for our own projects. The processor has plenty of GPIO, Analog inputs, hardware UART SPI and I2C, timers and PWM galore - just enough for most simple projects. When we need to go small, we use a <a...></a...>

Out of Stock
[Buy Now](https://www.adafruit.com/product/50)
[Related Guides to the Product](https://learn.adafruit.com/products/50/guides)

## Related Guides

- [Track Your Treats: Halloween Candy GPS Tracker](https://learn.adafruit.com/track-your-treats-halloween-candy-gps-tracker.md)
- [Naughty or Nice Machine](https://learn.adafruit.com/naughty-or-nice-machine.md)
- [Arduino Lesson 12. LCD Displays - Part 2](https://learn.adafruit.com/adafruit-arduino-lesson-12-lcd-displays-part-2.md)
- [Arduino Prototyping Mounting Plate](https://learn.adafruit.com/arduino-prototyping-mounting-plate.md)
- [8BitBox](https://learn.adafruit.com/8bitbox.md)
- [Memories of an Arduino](https://learn.adafruit.com/memories-of-an-arduino.md)
- [Arduino Lesson 16. Stepper Motors](https://learn.adafruit.com/adafruit-arduino-lesson-16-stepper-motors.md)
- [Line Following Zumo Robot Using Simulink](https://learn.adafruit.com/line-following-zumo-robot-programmed-with-simulink.md)
- [Using NeoPixels and Servos Together](https://learn.adafruit.com/neopixels-and-servos.md)
- [Programming Arduino with Android and Windows Tablets](https://learn.adafruit.com/programming-arduino-with-android-and-windows-tablets.md)
- [DS1307 Real Time Clock Breakout Board Kit](https://learn.adafruit.com/ds1307-real-time-clock-breakout-board-kit.md)
- [Arduino Lesson 0. Getting Started](https://learn.adafruit.com/lesson-0-getting-started.md)
- [Adafruit PN532 RFID/NFC Breakout and Shield](https://learn.adafruit.com/adafruit-pn532-rfid-nfc.md)
- [Wireless Power Switch with Arduino & the CC3000 WiFi Chip](https://learn.adafruit.com/wireless-power-switch-with-arduino-and-the-cc3000-wifi-chip.md)
- [Trinket Audio Player](https://learn.adafruit.com/trinket-audio-player.md)
