Cprogramming 简明教程

Functions in C

C 中的函数是一个有组织的可重用代码块,用于执行单个相关操作。每个 C 程序至少有一个函数,即 main() ,并且所有最简单的程序都可以定义其他函数。

A function in C is a block of organized reusuable code that is performs a single related action. Every C program has at least one function, which is main(), and all the most trivial programs can define additional functions.

当某个问题的算法涉及又长又复杂的逻辑时,它就会被分解成更小、更独立的可重用模块。这些小的代码块在不同的编程语言中称为不同的名称,如 modulesubroutinefunctionmethod

When the algorithm of a certain problem involves long and complex logic, it is broken into smaller, independent and reusable blocks. These small blocks of code are known by different names in different programming languages such as a module, a subroutine, a function or a method.

您可以将你的代码分为独立的功能。根据不同功能分割代码的方法由你决定,但从逻辑上讲,这样的划分是每个功能执行一项特定任务。

You can divide up your code into separate functions. How you divide up your code among different functions is up to you, but logically the division is such that each function performs a specific task.

一个函数 declaration 向编译器声明一个函数的名称、返回类型和参数。一个函数 definition 提供函数的实际主体。

A function declaration tells the compiler about a function’s name, return type, and parameters. A function definition provides the actual body of the function.

C 标准库提供了许多可以供您的程序调用的内置函数。例如, strcat() 拼接两个字符串, memcpy() 将一个内存地址复制到另一个地址,以及更多功能。

The C standard library provides numerous built-in functions that your program can call. For example, strcat() to concatenate two strings, memcpy() to copy one memory location to another location, and many more functions.

Modular Programming in C

函数被设计为执行一个作为整个过程一部分的特定任务。这种软件开发方法被称为 modular programming

Functions are designed to perform a specific task that is a part of an entire process. This approach towards software development is called modular programming.

模块化编程采用自上而下的方法进行软件开发。编程解决方案有一个主例程,通过它调用较小的独立模块(函数)。

Modular programming takes a top-down approach towards software development. The programming solution has a main routine through which smaller independent modules (functions) are called upon.

每个函数是一个独立、完整且可重用的软件组件。调用时,函数执行指定的任务并返回对调用例程的控制权,还可以选择返回其进程的结果。

Each function is a separate, complete and reusable software component. When called, a function performs a specified task and returns the control back to the calling routine, optionally along with result of its process.

这种方法的主要优点是代码易于遵循、开发和维护。

The main advantage of this approach is that the code becomes easy to follow, develop and maintain.

Library Functions in C

C 语言提供许多 library functions ,包括在不同的 header files 中。例如, stdio.h 标题文件包括 printf() 和 scanf() 函数。类似地, math.h 标题文件包含许多函数,如 sin()、pow()、sqrt() 等。

C offers a number of library functions included in different header files. For example, the stdio.h header file includes printf() and scanf() functions. Similarly, the math.h header file includes a number of functions such as sin(), pow(), sqrt() and more.

这些函数执行预定义的任务,可以在任何程序中根据要求调用它们。但是,如果您没有找到合适的功能库来服务您的目的,则可以定义一个。

These functions perform a predefined task and can be called upon in any program as per requirement. However, if you don’t find a suitable library function to serve your purpose, you can define one.

Defining a Function in C

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

In C, it is necessary to provide the forward 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.

在函数中的所有语句执行完毕后,程序的流将返回到调用环境。函数可能会随着流控制返回一些数据。

After all the statements in a function are executed, the flow of the program returns to the calling environment. The function may return some data along with the flow control.

Function Declarations in C

function declaration 告诉编译器函数名称和如何调用函数。函数的实际主体可以单独定义。

A function declaration tells the compiler about a function name and how to call the function. The actual body of the function can be defined separately.

一个函数声明有以下部分 −

A function declaration has the following parts −

return_type function_name(parameter list);

对于上述定义的函数 max(),函数声明如下所示 -

For the above defined function max(), the function declaration is as follows −

int max(int num1, int num2);

参数名称在函数声明中并不重要,只要求其类型,所以以下内容也是有效的声明 -

Parameter names are not important in function declaration only their type is required, so the following is also a valid declaration −

int max(int, int);

当你在一个源文件中定义函数并在那另一个文件中调用此函数时需要进行函数声明。在这种情况下,您应该在调用函数的文件顶部声明函数。

A function declaration is required when you define a function in one source file and you call that function in another file. In such cases, you should declare the function at the top of the file calling the function.

Parts of a Function in C

C 编程语言中函数定义的常规形式如下 -

The general form of a function definition in C programming language is as follows −

return_type function_name(parameter list){

   body of the function
}

C 编程中的函数定义包括函数头和函数体。以下是函数的所有部分 -

A function definition in C programming consists of a function header and a function body. Here are all the parts of a function −

  1. Return Type − A function may return a value. The return_type is the data type of the value the function returns. Some functions perform the desired operations without returning a value. In this case, the return_type is the keyword void.

  2. Function Name − This is the actual name of the function. The function name and the parameter list together constitute the function signature.

  3. Argument List − An argument (also called parameter) is like a placeholder. When a function is invoked, you pass a value as a parameter. This value is referred to as the actual parameter or argument. The parameter list refers to the type, order, and number of the parameters of a function. Parameters are optional; that is, a function may contain no parameters.

  4. Function Body − The function body contains a collection of statements that defines what the function does.

C 语言中的函数应该有返回值类型。函数返回变量的类型必须是函数的返回类型。在上图中,add() 函数返回 int 类型。

A function in C should have a return type. The type of the variable returned by the function must be the return type of the function. In the above figure, the add() function returns an int type.

Example: User-defined Function in C

在本程序中,我们使用了名为 max() 的用户定义函数。该函数接受两个参数 num1num2 ,并返回两者之间的最大值 −

In this program, we have used a user-defined function called max(). This function takes two parameters num1 and num2 and returns the maximum value between the two −

#include <stdio.h>

/* function returning the max between two numbers */
int max(int num1, int num2){

   /* local variable declaration */
   int result;

   if(num1 > num2)
      result = num1;
   else
      result = num2;

   return result;
}

int main(){
   printf("Comparing two numbers using max() function: \n");
   printf("Which of the two, 75 or 57, is greater than the other? \n");
   printf("The answer is: %d", max(75, 57));

   return 0;
}

当您运行此代码时,它将生成以下输出 −

When you runt this code, it will produce the following output −

Comparing two numbers using max() function:
Which of the two, 75 or 57, is greater than the other?
The answer is: 75

Calling a Function in C

在创建 C 函数时,您将对该函数的作用给出定义。要使用函数,您将必须调用该函数来执行已定义的任务。

While creating a C function, you give a definition of what the function has to do. To use a function, you will have to call that function to perform the defined task.

要正确调用函数,您需要遵守函数原型的声明。如果函数被定义为接收一组参数,则必须传递相同数量和类型的参数。

To call a function properly, you need to comply with the declaration of the function prototype. If the function is defined to receive a set of arguments, the same number and type of arguments must be passed.

当函数被定义为带参数时,函数名前面的参数被称为 formal arguments 。当调用函数时,传递给它的参数是 actual arguments

When a function is defined with arguments, the arguments in front of the function name are called formal arguments. When a function is called, the arguments passed to it are the actual arguments.

当程序调用函数时,程序控制被转移到被调用的函数。被调用的函数执行定义的任务,当执行其 return 语句或达到其函数结尾闭合大括号时,它将程序控制权返回到主程序。

When a program calls a function, the program control is transferred to the called function. A called function performs a defined task and when its return statement is executed or when its function-ending closing brace is reached, it returns the program control back to the main program.

Example: Calling a Function

要调用函数,您只需将所需的参数与函数名一起传递即可。如果函数返回一个值,那么您可以存储返回的值。请看以下示例 −

To call a function, you simply need to pass the required parameters along with the function name. If the function returns a value, then you can store the returned value. Take a look at the following example −

#include <stdio.h>

/* function declaration */
int max(int num1, int num2);

int main (){

   /* local variable definition */
   int a = 100;
   int b = 200;
   int ret;

   /* calling a function to get max value */
   ret = max(a, b);

   printf( "Max value is : %d\n", ret );

   return 0;
}

/* function returning the max between two numbers */
int max(int num1, int num2){

   /* local variable declaration */
   int result;

   if (num1 > num2)
      result = num1;
   else
      result = num2;

   return result;
}

我们将 max() 与 main() 一起保留并编译源代码。在运行最终可执行文件时,它将生成以下结果 −

We have kept max() along with main() and compiled the source code. While running the final executable, it would produce the following result −

Max value is : 200

The main() Function in C

C 程序是由一个或多个函数组成的集合,但其中一个函数必须被命名为 main() ,它是程序执行的入口点。

A C program is a collection of one or more functions, but one of the functions must be named as main(), which is the entry point of the execution of the program.

在 main() 函数内部,将调用其他函数。main() 函数可以调用库函数(例如带有原型从头文件 (stdio.h) 或代码中存在的任何其他用户定义函数的 printf())。

From inside the main() function, other functions are called. The main() function can call a library function such as printf(), whose prototype is fetched from the header file (stdio.h) or any other user-defined function present in the code.

在 C 中,程序定义的顺序并不重要。在一个程序中,无论何时有 main(),它都是入口点,不管它是否作为第一个函数存在。

In C, the order of definition of the program is not material. In a program, wherever there is main(), it is the entry point irrespective of whether it is the first function or not.

Note: 在 C 中,任何函数都可以随时多次调用任何其他函数。一个函数也可以调用它自己。这样的自调用函数被称为 recursive function

Note: 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.

Function Arguments

如果一个函数要使用参数,则它必须声明接收参数值的变量。这些变量称为函数的 formal parameters

If a function is to use arguments, it must declare variables that accept the values of the arguments. These variables are called the formal parameters of the function.

形式参数的行为类似于函数内的其他局部变量,并在进入函数时被创建,并在退出函数时被销毁。

Formal parameters behave like other local variables inside the function and are created upon entry into the function and destroyed upon exit.

在调用函数时,可以用两种方法将参数传递给函数 −

While calling a function, there are two ways in which arguments can be passed to a function −

Sr.No

Call Type & Description

1

Call by valueThis method copies the actual value of an argument into the formal parameter of the function. In this case, changes made to the parameter inside the function have no effect on the argument.

2

Call by referenceThis method copies the address of an argument into the formal parameter. Inside the function, the address is used to access the actual argument used in the call. This means that changes made to the parameter affect the argument.

默认情况下,C 使用 call by value 传递参数。一般来说,这意味着函数内的代码无法更改用于调用函数的参数。

By default, C uses call by value to pass arguments. In general, it means the code within a function cannot alter the arguments used to call the function.