C
C 语法

Functions

函数

函数是一种C语言结构,它将复合语句(函数体)与标识符(函数名称)关联起来。每个C程序都从主函数开始执行,主函数可以终止或调用其他用户定义或库函数。

// function definition. // defines a function with the name "sum" and with the body "{ return x+y; }" int sum(int x, int y) { return x + y; }

函数可以接受零个或多个参数,这些参数是从函数调用操作符的参数初始化的,并且可以通过返回语句将值返回给调用者。

int n = sum(1, 2 // parameters x and y are initialized with the arguments 1 and 2

函数的主体在函数定义中提供。除非函数内联,否则每个函数只能在程序中定义一次。

没有嵌套函数(除非通过非标准编译器扩展允许):每个函数定义必须出现在文件范围内,并且函数不能访问调用者的局部变量:

int main(void) // the main function definition { int sum(int, int // function declaration (may appear at any scope) int x = 1; // local variable in main sum(1, 2 // function call // int sum(int a, int b) // error: no nested functions // { // return a + b; // } } int sum(int a, int b) // function definition { // return x + a + b; // error: main's x is not accessible within sum return a + b; }

参考

  • C11 standard (ISO/IEC 9899:2011):