功能#

介绍#

函数是 C++ 编程的基本组成部分,它将代码片段打包成可重用、高效的代码段,用于执行特定任务。函数可以在一个程序中多次调用,从而简化代码组织,并有助于避免重复代码。函数还能使代码更易于调试。

This page covers the basics of using functions in C++, including:

Function Structure and Syntax#

在 C++ 中,函数必须声明其返回类型、名称和参数。基本语法如下:

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

功能部件

描述

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

函数的名称。

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.

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

Function Prototypes#

In C++, code is read from top to bottom. This means a function must be known to the compiler before it can be called.

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

Write the function’s body after

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

定义和调用函数#

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#

您还可以向函数添加参数,以便传递函数要使用的信息。

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

Return Values#

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

Passing By Reference#

By default, C++ passes function parameters by value, meaning the function receives a copy of the original variable. Changes made inside the function do not affect the original value.

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
}

Passing by reference allows functions to update variables defined outside the function without returning a value.

Callback Functions#

A callback function is a function that is passed into another function and called automatically when a specific event occurs.

Callbacks are commonly used for events such as button presses or sensor updates.

Instead of calling the function yourself, the project calls it for you when the event happens.

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#

Every callback function must follow a specific signature, which defines:

  • The return type

  • The number of parameters

  • The parameter types

The required signature is determined by the API. The callback function must match this signature exactly.

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

Parameter names are descriptive and may vary, but the return type, parameter order, and parameter types must match exactly.

具有默认参数的函数#

Functions can define default values for one or more parameters. A default argument is used when no value is provided for that parameter when the function is called.

Rules for default arguments:

  • Default arguments must be the last parameters in the function’s definition.

  • Once a parameter has a default value, all parameters after it must also have default values.

  • If a function specifies default arguments in its prototype, those default values must not be specified again in the function definition.

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 (IQ) and
  // use default value for repeatCount (1)
  greeting("IQ");

  Brain.Screen.newLine();

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