在main()之前或之后声明函数有什么区别? [英] What's the difference between declaring functions before or after main()?

查看:88
本文介绍了在main()之前或之后声明函数有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

之间有什么区别

void function();

int main()
{......}

void function()
{......}

vs

void function()
{.......}

int main();

当您可以在main之前声明并定义函数时,在main之前声明函数然后在main之后定义函数似乎很奇怪.是出于美学目的吗?我的老师写的函数类似于第一个示例.

It seems odd to declare a function before main then define it after main when you could just declare and define it before main. Is it for aesthetic purposes? My teacher writes functions like the first example.

推荐答案

它仅用于代码组织目的(我想是美学").如果没有前向声明,则需要在使用每个函数之前编写每个函数,但是出于组织目的,您可能希望以不同的顺序编写函数的主体.

It's just for code organization purposes ("aesthetics", I guess). Without forward declarations you'd need to write every function before it's used, but you may want to write the bodies of a function in a different order for organizational purposes.

使用前向声明还可以使您在文件的最顶部给出定义的功能列表,而不必深入研究实现.

Using forward declarations also allows you to give a list of the functions defined in a file at the very top, without having to dig down through the implementations.

在相互递归函数的情况下,前向声明也是必要的.考虑这个(愚蠢的)示例:

Forward declarations would also be necessary in the case of mutually recursive functions. Consider this (silly) example:

bool is_odd(int);  // neccesary

bool is_even(int x) {
  if (x == 0) {
    return true;
  } else {
    return is_odd(x - 1);
  }
}

bool is_odd(int x) {
  return is_even(x - 1);
}

这篇关于在main()之前或之后声明函数有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆