zoukankan      html  css  js  c++  java
  • C++关于函数声明定义的位置

    不知道刚开始学函数这块时,总以为要把函数声明放在函数定义前面,甚至有一种陷入框架的感觉,所以在此对此进行一下反思:

    根据C89规定,在任何执行语句之前,在块的开头声明所有局部变量。在C99以及C++中则没有这个限制,即在首次使用之前,可在块的任何位置都可以声明变量也就是说只要在你调用函数前,能让编译器找到你的调用函数的信息就可以了,并不一定是要在前面的

    我便搞了个代码试试:

    代码一:

    include<iostream>
    using namespace std; int max(int x, int y);//函数的声明 ,x,y是形参 int main() { int x, y, z; while (1) { cout << "请输入两个不同数值,以空格分开 "; cin >> x >> y; z = max(x, y); //函数的调用 ,此时x.y是实参 cout << "最大值是:" << z << endl; } } int max(int x, int y)//函数的定义 { int z; if (x > y) z = x; else z = y; return z; }

     代码二:

    #include<iostream>
    using namespace std;
    int max(int x, int y)//函数的定义
    {
        int z;
        if (x > y)
            z = x;
        else
            z = y;
        return z;
    }
    int main()
    {
        int x, y, z;
        while (1)
        {
            cout << "请输入两个不同数值,以空格分开
    ";
            cin >> x >> y;
            z = max(x, y); //函数的调用 
            cout << "最大值是:" << z << endl;
        }
        return 0;
    }

    调试后发现都没有报错,都可以得到正确的运行结果。由此可以得出下面结论:

    函数声明可以在main里面,也可以在main外面。

    如果放在main之前,就可以直接定义这个函数
    void func(int arg) {
    …;
    }//定义
     int main() {
    func();//声明
    }

    如果定义放在main之后就要在main之前先声明这个函数
    void func(int);//声明
    int main() {

    }
    void func(int arg) {
    …;
    }//定义

  • 相关阅读:
    MTK 定时器 休眠时的动作
    Troubleshooting MySQL Memory Usage
    disruptor
    Google Protocol Buffer 的使用和原理
    百度贴吧10亿量级LAMP架构分享
    nginx 不带www到www域名的重定向
    配置电信网通双线双IP的解决办法
    Create a W3C validated anchor link with target=“_blank”
    Could not update ICEauthority file /home/username/.ICEauthority
    Can't load IA 32bit .dll on a AMD 64bit platform
  • 原文地址:https://www.cnblogs.com/CX66/p/13907371.html
Copyright © 2011-2022 走看看