test Blog
Happy living

函数的定义,声明与原型

老鼠 posted @ 2009年4月07日 00:59 in 编程相关 with tags 函数原型 , 2369 阅读

       对函数的“定义”和“声明”不是一回事。“定义”是指对函数功能的确立,包括指定函数名,函数值类型、形参类型、函数体等,它是一个完整的、独立的函数单位。而“声明”的作用则是把函数的名字、函数类型以及形参类型、个数和顺序通知编译系统,以便在调用该函数时系统按此进行对照检查(例如函数名是否正确,实参与形参的类型和个数是否一致)。从程序中可以看到对函数的声明与函数定义中的函数首部基本上是相同的。因此可以简单地照写已定义的函数的首部,再加一个分号,就成为了对函数的“声明”。在函数声明中也可以不写形参名,而只写形参的类型。 在C语言中,函数声明称为函数原型(function prototype)。使用函数原型是ANSI C的一个重要特点。它的作用主要是利用它在程序的编译阶段对调用函数的合法性进行全面检查。

说明:

<1> 以前的C版本的函数声明方式不是采用函数原型,而只是声明函数名和函数类型。
如:float add(); 不包括参数类型和参数个数。系统不检查参数类型和参数个数。新版本也兼容这种用法,但不提倡这种用法,因为它未进行全面的检查。

<2> 实际上,如果在函数调用前,没有对函数作声明,则编译系统会把第一次遇到的该函数形式(函数定义或函数调用)作为函数的声明,并将函数类型默认为int型。如一个max函数,调用之前没有进行函数声明,编译时首先遇到的函数形式是函数调用"max(a, b)",由于对原型的处理是不考虑参数名的,因此系统将max()加上int作为函数声明,即int max(); 因此不少教材说,如果函数类型为整型,可以在函数调用前不必作函数声明。但是使用这种方法时,系统无法对参数的类型做检查。或调用函数时参数使用不当,在编译时也不会报错。因此,为了程序清晰和安全,建议都加以声明为好。

<3> 如果被调用函数的定义出现在主调函数之前,可以不必加以声明。因为编译系统已经先知道了已定义的函数类型,会根据函数首部提供的信息对函数的调用作正确性检查。

<4> 如果已在所有函数定义之前,在函数的外部已做了函数声明,则在各个主调用函数中不必对所调用的函数再作声明。

BSNL Landline Bill P 说:
2023年2月02日 16:52

BSNL bill payment online at quick pay portal with discount coupons and promo codes of 2023 without user login on portal2.bsnl.in, Find discount offers on different payment channels for online bill pay. BSNL Landline Bill Payment The new online web portal provided by Bharat Sanchar Nigam Limited allows loyalty rewards for each online transaction towards landline, mobile, broadband, fiber optic internet (FTTH) before or after the due date and even after disconnection.

CBSE 5th Class Syll 说:
2023年8月21日 19:35

CBSE Curriculum is based on the National Curriculum Framework and Provides Opportunities for Students to Achieve Excellence in Learning, CBSE Provides the Syllabus for 4th Class, This new Syllabus CBSE 5th Class Syllabus 2024 are Designed Strategically by a Team of Subject Experts and are Prescribed by the Ministry of Human Resource Development, formerly Ministry of Education, is Responsible for the Development of Human Resources in India, Primary Level Syllabus for the Children of has been developed with the Supervision of the Central Board of Secondary Education.

pavzi.com 说:
2024年1月27日 22:20

Pavzi.com is a startup by passionate webmasters and bloggers who have a passion for providing engaging content that is accurate, interesting, and worthy to read. pavzi.com We are more like a web community where you can find different information, resources, and topics on day-to-day incidents or news. We provide you with the finest web content on every topic possible with the help of the editorial and content team.


登录 *


loading captcha image...
(输入验证码)
or Ctrl+Enter