Variables#
Introducción#
Las variables almacenan datos y permiten reutilizarlos y manipularlos en todo el programa. C++ es un lenguaje estáticamente tipado, lo que significa que se debe declarar el tipo de una variable explícitamente al crearla. El tipo no se puede cambiar después de la declaración. Por ejemplo:
int angle = 90; // angle is an integer
char dist[] = "Distance"; // dist is an array of characters
double steps = 2.5; // steps is a double
C++ también es fuertemente tipado, lo que significa que no se pueden realizar operaciones con tipos incompatibles sin una conversión explícita. Por ejemplo:
int blocks = 2; // blocks is an integer
char rings[] = "4"; // rings is a string
int result = blocks + rings; // Creates a compilation error
Esta API explica los tipos de variables comunes en C++. Si bien no es una lista exhaustiva, abarca los tipos que probablemente usará en la práctica.
Variables locales — Se declaran dentro de una función y solo se usan dentro de ese ámbito; mejor para valores temporales o aislados.
Variables globales — Se declaran fuera de cualquier función y se utilizan en todo el proyecto; son útiles para compartir datos entre funciones.
Entero — Números enteros utilizados para contar, distancias o cualquier cosa sin decimales.
Doble — Números decimales de alta precisión para cálculos matemáticos que requieren exactitud.
Float — Números decimales de precisión estándar, útiles para mediciones o cálculos.
Cadena de estilo C — Valores de texto, utilizados para mensajes, etiquetas o para mostrar resultados legibles.
Boolean (bool) —
trueorfalsevalues for logic and decision-making.Arrays — Colecciones de tamaño fijo de elementos del mismo tipo.
Matrices 2D — Matrices de matrices; ideales para representar filas, cuadrículas o datos similares a tablas.
Const — A variable declared with
constcannot be modified.
Declaración y asignación de una variable#
To create a variable in C++, you must declare its type followed by the variable name, then optionally assign a value using the = operator:
int distance = 100;
Al nombrar una variable, se deben respetar las siguientes reglas:
El nombre no puede contener caracteres especiales (por ejemplo, un signo de exclamación).
El nombre no puede comenzar con un número.
El nombre no puede utilizar espacios.
The name cannot conflict with predefined VEXcode objects (for example,
Drivetrain).Variable names are case-sensitive (e.g.,
Distanceanddistanceare different variables).
Local Variables#
Las variables locales se definen dentro de una función o bloque de código. Solo son accesibles dentro del alcance de esa función o bloque y no son visibles fuera de él.
void show_local() {
// This variable only exists inside this function
int angle = 90;
Brain.Screen.print("%d", angle);
}
int main() {
// Initializing Robot Configuration. DO NOT REMOVE!
vexcodeInit();
// Begin project code
show_local();
}
Las variables locales se utilizan comúnmente para almacenar valores temporales que solo son relevantes dentro de una función o parte específica del programa.
Global Variables#
Las variables globales se definen fuera de cualquier función o bloque. Se puede acceder a ellas y leerlas en cualquier parte del programa, incluso dentro de las funciones.
Nota: Las variables globales son accesibles desde cualquier parte del programa, lo que facilita el intercambio de datos entre funciones. Sin embargo, depender excesivamente de ellas puede tener efectos secundarios no deseados, ya que los cambios en la variable en una parte del programa pueden afectar a otras partes de forma impredecible. Por esta razón, se prefieren las variables locales siempre que sea posible, ya que limitan el alcance de una variable a la función específica donde se define. Esto reduce la probabilidad de conflictos y facilita la depuración.
// The variable is defined outside a function
int angle = 90;
void show_global() {
// You can access 'angle' inside a function
Brain.Screen.print("%d", angle);
Brain.Screen.newLine();
}
int main() {
// Initializing Robot Configuration. DO NOT REMOVE!
vexcodeInit();
// Begin project code
show_global();
Brain.Screen.print("%d", angle);
}
In C++, global variables can be directly accessed and modified from within functions without any special keywords. However, if you have a local variable with the same name, you can use the scope resolution operator :: to access the global variable.
// Define the global variable
int count = 0;
void increase_count() {
// Global variables can be accessed directly
count = count + 1;
Brain.Screen.print("Count: %d", count);
Brain.Screen.newLine();
}
int main() {
// Initializing Robot Configuration. DO NOT REMOVE!
vexcodeInit();
// Begin project code
increase_count();
increase_count();
}
Tipos de datos#
C++ admite varios tipos de datos que se pueden almacenar en variables. Algunos tipos se pueden reasignar, mientras que otros permiten modificar elementos individuales. A continuación, se presentan los tipos más utilizados:
Integer#
Un entero (int) es un número entero.
int main() {
// Initializing Robot Configuration. DO NOT REMOVE!
vexcodeInit();
// Begin project code
int distance = 100;
// Move the robot forward for the variable value in mm
Drivetrain.driveFor(forward, distance, mm);
// Add to the variable and move forward the new value,
// for 200mm total
wait(1, seconds);
distance = distance + 100;
Drivetrain.driveFor(forward, distance, mm);
}
Double#
Un doble es un número de punto decimal con alta precisión (normalmente de 64 bits).
int main() {
// Initializing Robot Configuration. DO NOT REMOVE!
vexcodeInit();
// Begin project code
// Store a value with decimal points
double raw_value = 0.88;
// Print the decimal value as a percentage
Brain.Screen.print("%.1f%%", raw_value * 100);
}
Float#
Un valor flotante almacena números decimales. En la mayoría de los proyectos VEX, se prefieren los valores dobles (#double) a los flotantes, a menos que el uso de memoria sea un problema.
int main() {
// Initializing Robot Configuration. DO NOT REMOVE!
vexcodeInit();
// Begin project code
// Store a value with decimal points
float raw_value = 0.88;
// Print the decimal value as a percentage
Brain.Screen.print("%.1f%%", raw_value * 100);
}
String#
Una cadena de estilo C (char variable_name[]) es una secuencia de caracteres almacenados en una matriz de caracteres. Las cadenas de estilo C deben ser lo suficientemente grandes para almacenar el texto y un terminador nulo.
int main() {
// Initializing Robot Configuration. DO NOT REMOVE!
vexcodeInit();
// Begin project code
// Set the variable to a string then print the string
char message[] = "Ready!";
Brain.Screen.print(message);
}
Boolean#
A Boolean (bool) represents true or false values.
int main() {
// Initializing Robot Configuration. DO NOT REMOVE!
vexcodeInit();
// Begin project code
// Set the state of the variable
bool delivered = false;
// Print different messages depending on the Boolean.
if (delivered) {
Brain.Screen.print("Package delivered!");
} else {
Brain.Screen.print("Delivering...");
}
}
Los valores booleanos se pueden cambiar en cualquier momento del proyecto.
int main() {
// Initializing Robot Configuration. DO NOT REMOVE!
vexcodeInit();
// Begin project code
// Print the value of the delivered variable
bool delivered = false;
// Print different messages depending on the Boolean.
if (delivered) {
Brain.Screen.print("Package delivered!");
} else {
Brain.Screen.print("Delivering...");
}
wait(2, seconds);
// Clear the screen and print the value of the variable again
Brain.Screen.clearScreen();
Brain.Screen.setCursor(1,1);
delivered = true;
// Print different messages depending on the Boolean.
if (delivered) {
Brain.Screen.print("Package delivered!");
} else {
Brain.Screen.print("Delivering...");
}
}
Arrays#
Los arrays son conjuntos de elementos del mismo tipo con un tamaño fijo. Es recomendable conocer la longitud del array y declararlo al crearlo.
int main() {
// Initializing Robot Configuration. DO NOT REMOVE!
vexcodeInit();
// Begin project code
// Declare an array of 5 integers
int distances[5] = {100, 200, 150, 300, 250};
// Drive and turn 4 times to move the distance of the first four distance of the array
for (int i = 0; i < 4; i++) {
Drivetrain.driveFor(forward, distances[i], mm);
Drivetrain.turnFor(right, 90, degrees);
}
}
2D Arrays#
Una matriz 2D se usa comúnmente para representar cuadrículas, tablas o matrices. Cada fila representa una agrupación específica de datos.
int main() {
// Initializing Robot Configuration. DO NOT REMOVE!
vexcodeInit();
// Begin project code
// Assign the values in the matrix 2D array
int matrix[3][3] = {
{ 0, 1, 2 },
{ 3, 4, 5 },
{ 6, 7, 8 }
};
// Loop through each row
for (int i = 0; i < 3; i++) {
// Loop through each column in the row
for (int j = 0; j < 3; j++) {
Brain.Screen.print("%d, ", matrix[i][j]);
}
Brain.Screen.newLine();
}
}
Puede modificar elementos específicos dentro de una matriz 2D:
int main() {
// Initializing Robot Configuration. DO NOT REMOVE!
vexcodeInit();
// Begin project code
// Assign the values in the matrix 2D array
int matrix[3][3] = {
{ 0, 1, 2 },
{ 3, 4, 5 },
{ 6, 7, 8 }
};
// Modify the color (in column 2) in row 0
matrix[0][1] = 200;
// Print the modified row from the matrix 2D array
for (int j = 0; j < 3; j++) {
Brain.Screen.print("%d, ", matrix[0][j]);
}
}
Constant Variables#
A variable declared with const cannot be modified after it is initialized.
int main() {
// Initializing Robot Configuration. DO NOT REMOVE!
vexcodeInit();
const int maxSpeed = 100;
// maxSpeed can be used like a normal variable
Drivetrain.setDriveVelocity(maxSpeed, percent);
}