In this esp32/esp8266 tutorial we will check how to use the typedef keyword to create aliases for data types, on the Arduino core running on the ESP32 and on the ESP8266. The tests on the ESP32 were performed using a DFRobot’s ESP32 module device integrated in a ESP32 development board. The tests on the ESP8266 were performed on a DFRobot’s ESP8266 development board.
Introduction
In this tutorial we will check how to use the typedef keyword to create aliases for data types.
We will perform our tests on the Arduino core running both on the ESP32 and on the ESP8266. Nonetheless, this is a C/C++ language feature, so we should be able to use it in the Arduino environment to program any type of board.
As already mentioned, the typedef keyword allows for the creation os alias for data types, which can be used, for example, to replace a complex type name [1].
The basic syntax for the typedef keyword is the following:
We will start our code by creating an alias to the int data type. We will create an alias called integer. Following the syntax shown in the introductory section, we first use the typedef keyword, followed by the name of the type (int), followed by the alias (integer).
typedef int integer;
Moving on to the Arduino setup function, we start by opening a serial connection to output the results of our program.
Serial.begin(115200);
Next we will declare a variable of our defined alias. Basically, we will be declaring an int variable, but using a different name.
integer i = 10;
From this point onward, we use the variable i as an integer, independently of it being declared using an alias.
To illustrate this, we will declare an additional variable, which will be of type int. In this case, we will do the declaration without any alias.
int j = 20;
To finalize, we will print the sum of the two variables. As mentioned, the variable declared with an alias is an int, so they can be summed.
Serial.println(i+j);
You can check the final source code below.
typedef int integer;
void setup() {
Serial.begin(115200);
integer i = 10;
int j = 20;
Serial.println(i+j);
}
void loop() {}
Testing the code
To test the code, simply compile it and upload it to your device using the Arduino IDE. When it finishes, open the Serial Monitor. You should get an output similar to figure 1, which shows the sum of the two variables.
Unlock advanced smart home automations with the $8.9 DFRobot C4002 mmWave sensor. Learn to extract raw speed, energy, and direction data using ESPHome.
Need an ORP sensor? We compare entry-level Arduino meters, 24/7 online probes, and IP68 industrial RS485 sensors to help you build the best water IoT system.
This guide provides a side-by-side comparison and selection analysis for 5 core Electrical Conductivity (EC) sensors from DFRobot, helping you quickly identify the most suitable product based on measurement range (K-value), application scenario (industrial/laboratory), and system architecture (Analog/RS485).