Funciones#

Introducción#

Las funciones son un componente fundamental de la programación en C++, ya que agrupan fragmentos de código en secciones reutilizables y eficientes diseñadas para realizar una tarea específica. Se pueden llamar varias veces dentro de un programa, lo que facilita la organización del código y ayuda a evitar la repetición de código. Además, las funciones facilitan la depuración del código.

Esta página cubre los conceptos básicos del uso de funciones en C++, incluyendo:

Estructura y sintaxis de la función#

En C++, las funciones deben declararse con su tipo de retorno, nombre y parámetros. La sintaxis básica es:

return_type function_name(parameters) {
  // Code to execute when the function is called
  return result;  // Optional, used to return a value
}

Partes funcionales

Descripción

return_type

The data type that the function returns, some common options are:

  • void — Returns nothing
  • int — Returns an integer value
  • double — Returns a floating-point number
  • bool — Returns true or false
  • char — Returns a single character
  • const char* — Returns a text string
  • user-defined types — Returns a struct or class object

function_name

El nombre de la función.

parameters

Optional. A comma-separated list of typed parameters written as type name, where type specifies the data type of the parameter and name is the identifier used to access that value inside the function. Parameters receive input values when the function is called.

result

Optional. The value returned by the function. If the function’s return_type is not void, this value must be provided and its type must exactly match the specified return_type.

Nota: Una función debe **declararse antes de ser llamada, o debe proporcionar un prototipo de función.

Prototipos de funciones#

En C++, el código se lee de arriba abajo. Esto significa que el compilador debe conocer una función antes de poder llamarla.

A function prototype lets you use a function before writing its full code. This allows you to keep main() near the top of your program while placing function definitions later, where they are easier to organize and read.

Without a prototype, you would have to define every function above main(), which can make projects harder to follow as they grow.

Define the function prototype (outside of int main())

// The function's prototype
void greeting();

Call the function inside int main()

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

  greeting();
}

Escribe el cuerpo de la función después

void greeting() {
  Brain.Screen.print("Hello!");
}

Definición y llamada de funciones#

Functions with No Parameters#

If a function does not require input, you can define it without parameters. Use void as the return type if the function doesn’t return a value.

Define the function (outside of int main())

// Define a function to display a message
void greeting() {
    Brain.Screen.print("Hello!");
}

Call the function inside int main()

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

  // Call the function to display the message
  greeting();
}

Functions with Parameters#

También puedes añadir parámetros a las funciones, lo que te permite pasarles información para que la función la utilice.

Note: Text can be passed using C-style strings (const char*) or C++ strings (std::string).

Define the function (outside of int main())

// Define a function with a parameter
void namedGreeting(const char* name) {
    Brain.Screen.print("Hello, %s!", name);
}

Call the function with a parameter inside int main()

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

  // Call the function to display the message
  namedGreeting("Stranger");
}

Valores de retorno#

Functions can send data back to the caller using the return keyword. This allows you to capture and use the output in your project.

Define the function (outside of int main())

// Define a function that multiplies numbers by 2
int timesTwo(int number) {
    return number * 2;
}

Call the function with a parameter inside int main()

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

  // Display the return value
  Brain.Screen.print("%d", timesTwo(2));
}

Pasando por referencia#

Por defecto, C++ pasa los parámetros de las funciones por valor, lo que significa que la función recibe una copia de la variable original. Los cambios realizados dentro de la función no afectan al valor original.

Define the function (outside of int main())

// Add 1 to the number
void addOne(int number) {
  number++;
}

Call the function with a parameter inside int main()

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

  int value = 5;
  addOne(value);
  // "value" will still be 5
}

To allow a function to modify the original variable, parameters can be passed by reference using the & symbol.

Define the function (outside of int main())

// Add 1 to the number
void addOne(int& number) {
  number++;
}

Call the function with a parameter inside int main()

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

  int value = 5;
  addOne(value);
  // "value" will now be 6
}

El paso por referencia permite que las funciones actualicen variables definidas fuera de la función sin devolver un valor.

Funciones de devolución de llamada#

Una función de devolución de llamada es una función que se pasa a otra función y se llama automáticamente cuando ocurre un evento específico.

Las funciones de devolución de llamada se utilizan habitualmente para eventos como pulsaciones de botones o actualizaciones de sensores.

En lugar de que usted mismo llame a la función, el proyecto la llama automáticamente cuando ocurre el evento.

Define the callback function (outside of int main())

// Create a callback function
void onPressed() {
  Brain.Screen.print("Screen pressed!");
}

Register the callback inside int main()

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

  // Call onPressed whenever the screen is pressed
  Brain.Screen.pressed(onPressed);
}

Callback Signatures#

Cada función de devolución de llamada debe seguir una firma específica, que define:

  • El tipo de retorno

  • El número de parámetros

  • Los tipos de parámetros

La firma requerida viene determinada por la API. La función de devolución de llamada debe coincidir exactamente con esta firma.

// This callback function cannot include any parameters
void callback(void);

// This callback function includes four parameters
void callback(axisType axis, double x, double y, double z);

Los nombres de los parámetros son descriptivos y pueden variar, pero el tipo de retorno, el orden de los parámetros y los tipos de parámetros deben coincidir exactamente.

Funciones con argumentos predeterminados#

Las funciones pueden definir valores predeterminados para uno o más parámetros. Se utiliza un argumento predeterminado cuando no se proporciona ningún valor para ese parámetro al llamar a la función.

Reglas para los argumentos predeterminados:

  • Los argumentos predeterminados deben ser los últimos parámetros en la definición de la función.

  • Una vez que un parámetro tiene un valor predeterminado, todos los parámetros posteriores también deben tener valores predeterminados.

  • Si una función especifica argumentos predeterminados en su prototipo, esos valores predeterminados no deben especificarse nuevamente en la definición de la función.

Define the function (outside of int main())

// Required parameter first, default parameter last
void greeting(const char* name, int repeatCount = 1) {

    for (int i = 0; i < repeatCount; i++) {
        Brain.Screen.print("Hello, %s!", name);
        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();

  // Say what name to greet (EXP) and
  // use default value for repeatCount (1)
  greeting("EXP");

  Brain.Screen.newLine();

  // Overrides the default value to 3
  greeting("EXP", 3);
}

// Required parameter first, default parameter last
void greeting(const char* name, int repeatCount = 1) {

    for (int i = 0; i < repeatCount; i++) {
        Brain.Screen.print("Hello, %s!", name);
        Brain.Screen.newLine();
    }
}

int main() {
    vexcodeInit();

    // Say what name to greet (EXP) and
    // use default value for repeatCount (1)
    greeting("EXP");

    Brain.Screen.newLine();

    // Overrides the default value to 3
    greeting("EXP", 3);
}