命名空间
变体
操作

函数

来自 cppreference.cn
< c‎ | language

函数是 C 语言构造,它将复合语句(函数体)与标识符(函数名)关联起来。每个 C 程序都从main 函数开始执行,该函数要么终止,要么调用其他用户定义或库函数。

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

函数通过函数声明函数定义引入。

函数可以接受零个或多个形参,这些形参从函数调用运算符实参初始化,并且可以通过return 语句向其调用者返回值。

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

函数的函数体在函数定义中提供。每个在表达式中使用的内联(自 C99 起)函数(除非未求值)必须在程序中仅定义一次

没有嵌套函数(除非通过非标准编译器扩展允许):每个函数定义都必须出现在文件作用域中,并且函数无权访问来自调用者的局部变量

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

[编辑] 参考文献

  • C23 标准 (ISO/IEC 9899:2024)
  • 6.7.7.4 函数声明符(包括原型)(页码:待定)
  • 6.9.2 函数定义(页码:待定)
  • C17 标准 (ISO/IEC 9899:2018)
  • 6.7.6.3 函数声明符(包括原型)(页码:96-98)
  • 6.9.1 函数定义(页码:113-115)
  • C11 标准 (ISO/IEC 9899:2011)
  • 6.7.6.3 函数声明符(包括原型)(页码:133-136)
  • 6.9.1 函数定义(页码:156-158)
  • C99 标准 (ISO/IEC 9899:1999)
  • 6.7.5.3 函数声明符(包括原型)(页码:118-121)
  • 6.9.1 函数定义(页码:141-143)
  • C89/C90 标准 (ISO/IEC 9899:1990)
  • 3.5.4.3 函数声明符(包括原型)
  • 3.7.1 函数定义

[编辑] 参见

C++ 文档 关于 声明函数