• C Primer Plus(6) 中文版 第5章 运算符、表达式和语句 5.6 带参数的函数


    5.6 带参数的函数
    /* pound.c -- defines a function with an argument   */
    #include
    void pound(int n);   // ANSI function prototype declaration
    int main(void)
    {
        int times = 5;
        char ch = '!';   // ASCII code is 33
        float f = 6.0f;
        
        pound(times);    // int argument
        pound(ch);       // same as pound((int)ch);
        pound(f);        // same as pound((int)f);
        
        return 0;
    }

    void pound(int n)    // ANSI-style function header
    {                    // says takes one int argument
        while (n-- > 0)
            printf("#");
        printf("\n");

    /* 输出:

    */

    如果函数不接受任何参数,函数头的圆括号应该写上关键字void。
    参数名应遵循C语言的命名规则。
    声明参数就是创建了被称为形式参数(formal argument或formal parameter,简称形参)的变量。
    函数调用传递个值为实际参数(actual argument或actual parameter),简称实参。 
    注意 实参和形参
    C99标准规定了:对于实参使用术语actual argument;对于形参使用术语formal parameter。 
    为遵循这一规定,我们可以说形参是变量,实参是函数调用提供的值,实参被赋给相应的形参。
    变量名是函数私有的,即在函数中定义的变量不会和别处的相同名称发生冲突。
    原型(prototype)即是函数的声明,描述了函数的返回值和参数。
    返回值类型为void表明没有返回值。
    当实参也形参类型不同时,会导致实参向形参类型进行转换。
    在ANSI C之前,C使用的是函数说明,而不是函数原型。函数说明只指明了函数名和返回类型,没有指明参数类型。为了向下兼容,
    C现在仍然允许这样的形式:
    void pound(); /*ANSI C之前的函数声明*/
    缺少函数原型,C也会把char和short类型自动升级为int类型。float会被自动升级为double,这没什么用虽然程序仍然能运行,但是输出的内容不正确。在函数调用中显示使用强制类型转换,可以修复这个问题:
    pound( (int)f ); //把f转换转换为正确的类型
    注意,如果f的值太大,超过了int类型的范围,这样做也不行。 

  • 相关阅读:
    10.什么是递归插槽及使用方式
    SVN使用总结
    Revit二次开发——族的基础
    ONNX--学习笔记
    Golang操作数据库简单示例
    修改设备网络DNS
    codeWarrior中乘法运算问题记录
    命令模式
    golang学习笔记——查找质数
    KVM 虚拟化
  • 原文地址:https://blog.csdn.net/weixin_40186813/article/details/126196349