Cprogramming 简明教程

User-defined Functions in C

C 中的 function 是一个有组织的可重用代码块,用于执行一个相关的操作。在任何 C 程序中,都有一个或多个函数 − 分为库函数和用户定义函数。

A function in C is a block of organized, reusable code that is used to perform a single related action. In any C program, there are one or more functions − classified as library functions and user-defined functions.

在 C 中有两种类型的函数 −

There are two types of functions in C −

  1. Library functions

  2. User-defined functions

任何 C 编译器(例如,GCC 编译器、Clang、MSVC 编译器等)都预编译一系列头文件( stdio.hmath.h 等)进行分发,每个文件包括一个或多个预定义库函数,例如 printf()scanf()pow()sqrt() 等。若要使用库函数,必须通过 #include 指令提供相应的文件。

Any C compiler (e.g. GCC compiler, Clang, MSVC compiler, etc.) is distributed with a number precompiled header files (stdio.h, math.h, etc.), each consisting of one or more predefined library functions such as printf(), scanf(), pow(), sqrt(), etc. To be able to use the library function, the corresponding header file must be made available with the #include directive.

但是,如果您找不到合适的库函数来达到您的目的,那么可以为该程序定义一个自定义函数。通常,我们发现一个包含 main() function 的 C 程序。显然,main() 函数是一个用户自定义函数,因为它包含用户提供的指令。它当然能够调用其他库或用户自定义函数。

However, if you don’t find a suitable library function to serve your purpose, then you can define a customized function for the program. Normally, we find a C program with a main() function. Obviously, the main() function is a user-defined function, as it contains the instructions provided by the user. It can of course call the other library or user-defined functions.

What is User-Defined Function in C?

User-defined function 由用户定义,用于执行特定的任务以实现代码的可重用性和模块性。要创建和使用用户自定义函数,您不需要使用任何内置库。这些函数既可以在同一程序中创建,也可以在用户自定义的头文件中创建。

User-defined function is defined by the user to perform specific task to achieve the code reusability and modularity. To create and use the user-defined function, you do not need use any built-in library. These functions can be created either in the same program or in user-defined header file.

Creating a User-defined Function

若要创建用户自定义函数,首先需要了解该函数的目的,即,您想让该函数执行什么操作?

For creating a user-defined function, first you need to understand the purpose of the function, that is, what do you want the function to do?

若要创建用户自定义函数,您需要了解该函数的以下三个部分:

To create a user-defined function, you need to know about the following three parts of a function:

  1. Function declaration

  2. Function definition

  3. Function calling

Declaration of User-defined Function

在 C 语言中,提供任何函数原型的声明是必要的。库函数的原型存在于相应的文件中。

In C language, it is necessary to provide the declaration of the prototype of any function. The prototype of a library function is present in the corresponding header file.

对于用户自定义函数,其原型存在于当前程序中。函数的定义及其原型声明应匹配。

For a user-defined function, its prototype is present in the current program. The definition of a function and its prototype declaration should match.

如果您希望定义一个名为 add() 的函数,该函数执行两个整数参数的加法并返回一个整数作为值,那么函数声明如下 −

If you wish to define a function called add() that performs the addition of two integer arguments and returns the value as an integer, then the function declaration would be as follows −

int add(int, int);

Definition of User-defined Function

函数的定义及其原型声明应匹配。定义包括与声明和函数体匹配的函数头。

The definition of a function and its prototype declaration should match. The definition consists of a function header that matches the declaration and a function body.

return_type function_name(arg1, arg2, ...){

   // Function body;

   return val;

}

使用此模板,您可以如下编写用户自定义函数 add() −

Using this template, you can write the user-defined function add() as follows −

int add(int a, int b){
   int c;
   c = a + b;
   return c;
}

请注意,在 C 程序中,自定义函数的定义顺序并不重要。但是,在调用函数之前,必须声明其原型。

Note that the order of definition of user-defined functions is not important in a C program. However, its prototype must be declared before calling the function.

在程序中,main() 函数始终是入口点,无论它是否是第一个函数。我们不需要提供 main() 函数的原型声明。

In a program, the main() function is always the entry point, irrespective of whether it is the first function or not. We needn’t provide the prototype declaration of the main() function.

Calling a User-defined Function

若要调用该函数,您应使用符合函数原型声明的语句。如果该函数被定义为接受一定数量的参数,那么必须传递相同数量和类型的参数来调用该函数。

To call a function, you should use a statement that complies with the declaration of the function prototype. If the function is defined to receive a certain number of arguments, then the same number and type of arguments must be passed to call that function.

以下语句调用我们在上面定义的 add() 函数 −

The following statement calls the add() function that we defined above −

int result = add(10, 20);

Example of User-Defined Function

在此示例中,我们会创建两个用户自定义函数 add()sub() ,以查找给定数字的加法和减法。

In this example, we are create two user-defined functions add() and sub() to find the addition and subtraction of the given numbers.

// C program to demonstrate an example of
// user-defined function
#include <stdio.h>

// Function declarations
int add(int, int);
int sub(int, int);

// Function definitions
int add(int a, int b) {
  return (a + b);
}

int sub(int a, int b) {
  return (a - b);
}

int main() {
  // Declaring two integer variables to
  // store the numbers
  // and resultant variables to store the result
  int num1 = 36, num2 = 24;
  int res_add, res_sub;

  // Calling the functions
  res_add = add(num1, num2);
  res_sub = sub(num1, num2);

  // Printing the results
  printf("Addition is : %d\n", res_add);
  printf("Subtraction is : %d\n", res_sub);

  return 0;
}
Addition is : 60
Subtraction is : 12

Formal and Actual Arguments in User-Defined Function

当函数使用参数定义时,函数名称前括号中的参数称为 formal arguments 。在上面的示例中,该函数使用“int a”和“int b”参数来定义;它们是形式参数。

When a function is defined with arguments, the arguments in the parenthesis in front of the function name are called formal arguments. In the above example, the function is defined with "int a" and "int b" arguments; they are formal arguments.

当调用该函数时,传递给它的参数称为 actual arguments 。在下面的示例中,变量“x”和“y”是实际参数。

When the function is called, the arguments passed to it are called the actual arguments. In the example below, the variables "x" and "y" are the actual arguments.

int x = 10, y = 20;
int result = add(x, y);

可以将用户自定义函数定义为具有任何类型的变量作为形式参数。它包括基本类型(int、float、char)、数组、指针或结构/联合类型变量。

A user-defined function may be defined to have any type of variables as formal arguments. It includes primary types (int, float, char), array, pointer, or struct/union type variables.

函数应向调用环境返回一个值。默认情况下,函数的返回类型为 int 类型。但是,它可以返回任何数据类型 − 基本类型、数组、指针或者结构以及指针。您甚至可以定义返回 void 类型的函数。

A function should return a value to the calling environment. By default, the return type of a function is int type. However, it can return any data type − primary type, array, pointer, or a struct as well as a pointer. You can even define a function that returns a void type.

Example

如果实际参数和形式参数的数量或类型或者返回类型与函数的前向声明及其定义中的不匹配,则编译器会报告错误。

If either the number or the type of actual and formal arguments or the return type as in the forward declaration of a function and its definition don’t match, then the compiler reports an error.

请看以下示例 −

Look at the example below −

#include <stdio.h>

float divide (int, int);

int main(){

   int x = 15, y = 5;

   float z = divide (x, y);

   printf("%f", z);

   return 0;
}

int divide (int a, int b){

   int c = a/b;

   return c;
}

在上面的代码中,divide() 函数的声明与它的定义不匹配,因此编译器显示以下错误 −

In the code above, the declaration of the divide() function doesn’t match with its definition, hence the compiler shows the following error −

error: conflicting types for 'divide'

在 C 中,任何函数都可以调用任何其他函数,次数不限。函数也可以调用自身。这种自调函数被称为 recursive function

In C, any function can call any other function, any number of times. A function can call itself too. Such a self-calling function is called a recursive function.

以下程序从 main() 内部调用 main() 函数 −

The following program calls the main() function from inside main() itself −

#include <stdio.h>

int main(){

   printf("Hello");

   main();

   return 0;
}

执行时,程序进入无限循环。在实践中,必须使用 recursion ,以便程序最终终止。

When executed, the program goes into an infinite loop. In practice, recursion has to be used so that the program eventually terminates.