CPP cheat sheet - Robosoc-Southampton/Tutorials GitHub Wiki

Contents

Defining variables

<type> <name>;
<type> <name> = <value>;
int x = 1;
Servo grabber;

Calling functions

<name>(<parameters>);
<type> <variable name> = <name>(<parameters>);
digitalWrite(LED_BUILTIN, HIGH);
Serial.println("hello world");
bool value = digitalRead(MY_PIN);

If statements and loops

Note: These are covered in the Week 1 programming tutorial.

If statement

if (<condition>) {
    <code>
}
else {
    <code>
}
if (x > 1) {
    Serial.print("X is ");
    Serial.println(x);
}

For loops

for (<init>; <condition>; <update>) {
    <code>
}
for (int i = 0; i < 10; ++i) {
    Serial.println(i);
}

While loops

while (<condition>) {
    <code>
}
while (angle < 10) {
    turn();
}

Defining functions

<type> <name>(<parameters>) {
    <code>
}
int add(int x) {
    return x + 1;
}

Variables

Variables are storage containers for information. They can be given (almost) any name dependent on the programmer's preference. Variables always have a type. This type tells the compiler what you can put in the variable, what you are allowed to do with the variable, and how it’s gonna be used.

somevar
Any_VariABle

Types

Types - Numbers

int (integer)

The main workhorse, stores a number in 2 bytes (16 bits) (on an Arduino). Has no decimal places and will store a value between -32,768 and 32,767.

5
256
-47528

long (big integer)

Used when an int is not large enough. Takes 4 bytes to store (32 bits) (on an Arduino) and has a range between -2,147,483,648 and 2,147,483,647.

5 //you can still have smaller numbers as longs but it is a waste of memory πŸ‘ 
256123214
-4752823

boolean (true/false)

A simple True or False variable (also can be thought of like 1 or 0). Useful because it only uses one bit.

true
false
1

float (decimal number)

Used for floating-point mathematics (decimals). Takes 4 bytes to store (32 bits) and has a range between -3.4028235E+38 and 3.4028235E+38 (- yes it's BIG).

5.0 //once again a non-decimal number can be set but it is a waste of memory
0.10298
-3.213492
231421.7

Types - Letters and Words

char (character)

Stores one character using the ASCII code (ie 'A' = 65). Uses one byte to store (8 bits). A string of text is usually represented as a list of chars.

'a'
'?'

Strings (string)

A bunch of characters put together to create words, sentences etc. It uses double quotes around the data vs. the char which uses single quotes.

"hello world"
"I am a \"string\""

Remember to assign the right types of values to a certain type of variable. If you try to assign 1.5 to a variable of type int, one of two things will happen. Either the compiler (the thing that builds the code you write) will give and error or the number will be shortened to 1, ergo it does not round!

⚠️ **GitHub.com Fallback** ⚠️