首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

Functions

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

代码语言:javascript
复制
// 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;
}

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

代码语言:javascript
复制
int n = sum(1, 2); // parameters x and y are initialized with the arguments 1 and 2

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

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

代码语言:javascript
复制
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):
    • 6.7.6.3 Function declarators (including prototypes) (p: 133-136)
    • 6.9.1 Function definitions (p: 156-158)
  • C99 standard (ISO/IEC 9899:1999):
    • 6.7.5.3 Function declarators (including prototypes) (p: 118-121)
    • 6.9.1 Function definitions (p: 141-143)
  • C89/C90 standard (ISO/IEC 9899:1990):
    • 3.5.4.3 Function declarators (including prototypes)
    • 3.7.1 Function definitions

扫码关注腾讯云开发者

领取腾讯云代金券

http://www.vxiaotou.com