Funciones#
Introducción#
Las funciones son un componente fundamental de la programación en C++, ya que empaquetan 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. Además, facilitan la depuración del código.
En C++, las funciones deben declararse con su tipo de retorno, nombre y parámetros. La sintaxis básica es:
Uso:
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 |
---|---|
|
The data type that the function returns ( |
|
El nombre de la función. |
|
Opcional. Variables que aceptan valores de entrada cuando se llama a la función, lo que permite pasar datos a la función. |
|
Optional. Let the function send a result back to the caller. If a function has a return type other than |
Nota: Una función debe siempre ser declarada antes de ser llamada, o debe proporcionar un prototipo de función.
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 a function to display a message
void greeting() {
Brain.Screen.print("Hello!");
}
int main() {
// Initializing Robot Configuration. DO NOT REMOVE!
vexcodeInit();
// Call the function to display the message
greeting();
}
Functions with Parameters#
También puedes agregar parámetros a las funciones, lo que te permite pasar información para que la función la utilice.
// Define a function with a parameter
void named_greeting(char name[]) {
Brain.Screen.print("Hello, %s!", name);
}
int main() {
// Initializing Robot Configuration. DO NOT REMOVE!
vexcodeInit();
named_greeting("Stranger");
}
Functions with Default Arguments#
Un argumento predeterminado es un parámetro que asume un valor predeterminado si no se proporciona un valor en la llamada de función para ese argumento.
// Define a function with a parameter and a default argument
void named_greeting(char name[] = "Stranger") {
Brain.Screen.print("Hello, %s!", name);
}
int main() {
// Initializing Robot Configuration. DO NOT REMOVE!
vexcodeInit();
// Use the default argument
named_greeting();
Brain.Screen.newLine();
// Change the parameter to a different name
named_greeting("IQ");
}
Return Values from Functions#
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 a function that multiplies numbers by 2
int times_two(int number) {
return number * 2;
}
int main() {
// Initializing Robot Configuration. DO NOT REMOVE!
vexcodeInit();
// Display the return value
Brain.Screen.print("%d", times_two(2));
}