Functions#

Introduction#

Functions are a fundamental component of C++ programming, packaging code snippets into reusable, efficient sections of code designed to perform a specific task. Functions can be called multiple times within a program, making code organization easier, and helping to avoid repeated code. Functions also make code easier to debug.

In C++, functions must be declared with their return type, name, and parameters. The basic syntax is:

Usage:

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

Function Parts

Description

return_type

The data type that the function returns (void if there is no return value).

function_name

The name of the function.

parameters

Optional. Variables that accept input values when the function is called, allowing data to be passed into the function.

result

Optional. Let the function send a result back to the caller. If a function has a return type other than void, it must return a value.

Note: A function must always be declared before it is called, or you must provide a function prototype.

Defining and Calling Functions#

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#

You can also add parameters to functions, which let you pass in information for the function to use.

// 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#

A default argument is a parameter that assumes a default value if a value is not provided in the function call for that argument.

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