Variables#

Introducción#

Las variables almacenan datos y permiten reutilizarlos y manipularlos a lo largo del programa. C++ es un lenguaje de tipado estático, lo que significa que se debe declarar explícitamente el tipo de una variable 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 más comunes en C++. Si bien no es una lista exhaustiva, abarca los tipos que probablemente usarás con mayor frecuencia en la práctica.

  • Variables locales — Declaradas dentro de una función y utilizadas únicamente dentro de ese ámbito; ideales para valores temporales o aislados.

  • Variables globales — Declaradas fuera de cualquier función y utilizadas en todo el proyecto; útiles para compartir datos entre funciones.

  • Entero — Números enteros utilizados para contar, distancias o cualquier cosa sin decimales.

  • Double — 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 una salida legible.

  • Boolean (bool)true or false values for logic and decision-making.

  • Matrices — Colecciones de tamaño fijo de elementos del mismo tipo.

  • Matrices 2D — Matrices de matrices; ideales para representar filas, cuadrículas o datos tipo tabla.

  • Const — A variable declared with const cannot be modified.

Declarar y asignar 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 seguir 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 contener espacios.

  • The name cannot conflict with predefined VEXcode objects (for example, Drivetrain).

  • Variable names are case-sensitive (e.g., Distance and distance are different variables).

Local Variables#

Las variables locales se definen dentro de una función o bloque de código. Solo son accesibles dentro del ámbito de esa función o bloque y no son visibles fuera de él.

Define the function (outside of int main())

void show_local() {
  // This variable only exists inside this function
  int angle = 90;
  Brain.Screen.print("%d", angle);
}

Call the function inside int main()

int main() {
  /* vexcodeInit() is only required when using VEXcode.
  Remove vexcodeInit() if compiling in VS Code. */
  vexcodeInit();

  // Begin project code
  show_local();
}

Las variables locales se utilizan habitualmente para almacenar valores temporales que solo son relevantes dentro de una función específica o una parte 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 compartir datos entre funciones. Sin embargo, depender excesivamente de las variables globales puede provocar efectos secundarios no deseados, ya que los cambios en una variable en una parte del programa pueden afectar a otras partes de forma impredecible. Por este motivo, generalmente se prefieren las variables locales cuando 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.

Define the function (outside of int main())

// 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();
}

Call the function inside int main()

int main() {
  /* vexcodeInit() is only required when using VEXcode.
  Remove vexcodeInit() if compiling in VS Code. */
  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 function (outside of int main())

// 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();
}

Call the function inside int main()

int main() {
  /* vexcodeInit() is only required when using VEXcode.
  Remove vexcodeInit() if compiling in VS Code. */
  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 muestran 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 double es un número decimal de 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 float almacena números decimales. En la mayoría de los proyectos VEX, se prefieren los doubles a los floats 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 almacenada en una matriz de caracteres. Las cadenas de estilo C deben ser lo suficientemente largas como 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 modificar 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 colecciones de tamaño fijo de elementos del mismo tipo. Es recomendable conocer la longitud del array y declararla al momento de su creación.

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 bidimensional 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();
  }
}

Puedes 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);
}