In C++ there are several variable types that you can use in different ways. Let’s start with the text “Hello, World!”. This text should now be stored in a variable for text.
The easiest way to do this in the Arduino IDE is with the type String. Let’s take a brief look at variable declaration.
Declaring Variables
Declaring variables is quite simple and always follows the same principle:
Type Name = Value;
In our case that would be:
String text = "Hello, World";
Let’s briefly talk about variable names. In principle, there are no limits to your imagination here. However, there are some names that you cannot use because they are already assigned to other functions in C++.
These include, for example: if, else, continue, class and true.
The list of reserved words is long – but fortunately you don’t have to memorize them. Whenever you use a variable name during declaration that is already reserved elsewhere, the name will be colored (allowed names remain black) and at the latest when uploading the sketch, you will receive an error message.
Also, you cannot start variable names with a number or a special character.
However, you can write variable names in upper or lower case. It is common practice to begin a variable name with lowercase. If the name consists of two or more words, the so-called Camel Case is used. Here you begin the first word with lowercase and start all further words with an uppercase letter:
myCamelVariable
With some imagination, you can see the humps of a camel here, well… 😉 One final tip: Try to give variables names that describe their purpose well. This helps you and other readers of your code understand what is stored in them.
Other Types of Variables
Besides text, there are of course also numbers. There are several types for this, depending on what kind of number it is:
Type | Suitable for | Numeric range |
---|---|---|
int | Whole numbers | -32,768 to 32,767 |
long | Whole numbers | -2,000,000,000 to 2,000,000,000 |
float | Floating point numbers | -3.4028235E+38 to 3.4028235E+38 (yes, very large) |
As we continue with the course, we will use variables of the type int – i.e., whole numbers. And one very special type: bool. Variables of type bool can only take two values or states: True or False.
In the next lesson, we’ll continue with variables – in practice. 🙂