关于C函数的参数个数的问题

本文引自:http://c.biancheng.net/cpp/html/1592.html

一个函数的参数的数目没有明确的限制,但是参数过多(例如超过8个)显然是一种不可取的编程风格。参数的数目直接影响调用函数的速度,参数越多,调用函数就越慢。另一方面,参数的数目少,程序就显得精练、简洁,这有助于检查和发现程序中的错误。因此,通常应该尽可能减少参数的数目,如果一个函数的参数超过4个,你就应该考虑一下函数是否编写得当。

如果一个函数不得不使用很多参数,你可以定义一个结构来容纳这些参数,这是一种非常好的解决方法。在下例中,函数print_report()需要使用10个参数,然而在它的说明中并没有列出这些参数,而是通过一个RPT_PARMS结构得到这些参数。

# include <atdio. h>
typedef struct
(
    int      orientation ;
    char     rpt_name[25];
    char     rpt_path[40];
    int      destination;
    char     output_file[25];
    int      starting_page;
    int      ending_page;
    char     db_name[25];
    char     db_path[40];
    int      draft_quality;
)RPT_PARMS;
void main (void);
int print_report (RPT_PARMS* );
void main (void)
{
    RPT_PARMS    rpt_parm; /*define the report parameter
                              structure variable * /
     /* set up the report parameter structure variable to pass to the
     print_report 0 function */
    rpt_parm. orientation = ORIENT_LANDSCAPE;
    rpt_parm.rpt_name = "QSALES.RPT";
    rpt_parm. rpt_path = "CiREPORTS"
    rpt_parm. destination == DEST_FILE;
    rpt_parm. output_file = "QSALES. TXT" ;
    rpt_parm. starting_page = 1;
    rpt_pann. ending_page = RPT_END;
    rpt_pann.db_name = "SALES. DB";
   rpt_parm.db_path = "CiDATA";
   rpt_pann. draft_quality = TRUE;
    /*call the print_report 0 function; paaaing it a pointer to the
       parameteM inatead of paMing it a long liat of 10 aeparate
       parameteM.  * /
    ret_code = print_report(cu*pt_parm);
}
int print_report(RPT_PARMS*p)
{
    int rc;
    /*acccM  the report parametcra paaaed to the print_report()
       function */
    oricnt_printcr(p->orientation);
    Kt_printer_quality((p->draft_quality == TRUE) ? DRAFT ; NORMAL);
     return rc;
}

上例唯一的不足是编译程序无法检查引用print_report()函数时RPT_PARMS结构的10个成员是否符合要求。

原文地址:https://www.cnblogs.com/blogofwu/p/4208685.html