CPP cheat sheet - Robosoc-Southampton/Tutorials GitHub Wiki
<type> <name>;
<type> <name> = <value>;
int x = 1;
Servo grabber;
<name>(<parameters>);
<type> <variable name> = <name>(<parameters>);
digitalWrite(LED_BUILTIN, HIGH);
Serial.println("hello world");
bool value = digitalRead(MY_PIN);
Note: These are covered in the Week 1 programming tutorial.
if (<condition>) {
<code>
}
else {
<code>
}
if (x > 1) {
Serial.print("X is ");
Serial.println(x);
}
for (<init>; <condition>; <update>) {
<code>
}
for (int i = 0; i < 10; ++i) {
Serial.println(i);
}
while (<condition>) {
<code>
}
while (angle < 10) {
turn();
}
<type> <name>(<parameters>) {
<code>
}
int add(int x) {
return x + 1;
}
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
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
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
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
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
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'
'?'
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!