之间的区别是什么:main(){},int main(){}和int main(void){} [英] What are the differences between: main(){}, int main(){} and int main(void){}

查看:116
本文介绍了之间的区别是什么:main(){},int main(){}和int main(void){}的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在学习C,并且已经编写了许多小程序.但是,我注意到主要功能可能会以

I am currently learning C and I have written many small programs. However, I have noticed that the main function could start as

    main()
    {
       //code
    }

    int main()
    {
      //code
      return 0;
    }

    int main(void)
    {
       //code
       return 0;
    }

我应该使用哪个选项?谢谢!

Which option should I use? Thanks!

推荐答案

您的第一个示例-使用了从C的过时方言继承的功能,该功能早于第一个ANSI(1989)和ISO(1990)标准:即,您可以编写一个不指定返回类型的函数,在这种情况下,该类型的缺省值为int.

Your first example uses a feature inherited from the outdated dialect of C which predated the first ANSI(1989) and ISO(1990) standard: namely, that you can write a function which doesn't specify its return type, and in that case the type defaults to int.

在C早期,void关键字和关联的类型不存在.当程序员想要编写过程(具有副作用但不返回任何东西的函数")时,他们使用此功能对其进行了模拟.他们编写了一个没有指定返回类型的关键字的函数.他们允许函数在不返回值的情况下执行最后一条语句(或者,他们使用return;从中间退出而不提供值),并且将调用写入函数,以使这些调用不会尝试执行使用返回值:

In early C, the void keyword and associated type did not exist. When programmers wanted to write procedures ("functions that have a side effect, but do not return anything"), they simulated it using this feature. They wrote a function without any keyword specifying the return type. They allowed the function to execute to it last statement without returning a value (or alternatively, they used return; to exit from the middle without supplying a value), and they wrote the calls to the function such that those calls did not try to use the return value:

parse_input() /* similar to a procedure in Pascal, but fake! */
{
   /* ... */
   if (condition())
     return; /* no value */
   /* ... */
   /* fall off end here */
}

int main()
{
   parse_input(); /* no return value extracted, everything cool! */
   return 0;
}

不幸的是,一些程序员也开始不在乎程序的终止状态,而是以以下过程样式编写main本身:

Unfortunately, some programmers also started not caring about the termination status of a program and writing main itself in this procedure style:

main()
{
  /* do something */
  /* fall off the end without returning a value */
}

(还存在一种混合样式:省略int声明符,但返回一个整数值.)

(A mixed style also existed: omitting the int declarator but returning an integer value.)

这些程序无法返回值,其终止状态不确定.对于操作系统,它们的执行可能成功或失败. 试图依靠这种程序的终止状态的脚本编写者感到痛苦!

These programs failing to return a value had an indeterminate termination status. To the operating system, their execution could look successful or failed. Woe to the script writer who tried to depend on the termination status of such a program!

然后情况变得更糟了. C ++出现并引入了void,并被C所采用.使用C ++中的void关键字,可以声明一个实际上不返回任何内容的函数(在任何其他函数中具有return;语句都将导致错误.一种功能).曾经写没有返回类型的main的虚拟程序员变得笨拙,并开始将这种新的C ++ void放在前面:

Then things took a turn for the worse. C++ came along and introduced void, and it was adopted into C. With the void keyword in C++, one could declare a function that actually returns nothing (and make it an error to have a return; statement in any other kind of function). The dummy programmers who used to write main with no return type got dumber, and started sticking this new-fangled, fresh-out-of-C++ void in front:

void main() /* yikes! */
{
  /* do something */
  /* fall off the end without returning a value */
}

这一次他们忘记了当他们写main()时,实际上是int main()的意思,这使函数具有与环境调用的启动调用兼容的类型(除了忽略返回a的问题之外).价值).现在它们实际上具有与预期功能不同的功能类型,甚至可能无法成功调用!

By this time they had forgotten that when they wrote main(), it actually meant int main(), which made the function have a compatible type with the startup call invoked by the environment (except for the matter of neglecting to return a value). Now they actually had a different function type from the expected one, which might not even be successfully called!

现在的情况是,在C ++和最新的C ++标准中,仍需要main返回int.但是两种语言都对原始的虚拟程序员让步:您可以让执行掉线"到main的结尾,并且行为就好像在其中执行了return 0;一样.因此,这个琐碎的程序现在具有从C99到C ++ 98(或更早的版本)的成功终止状态:

Where things stand now is that in C++ and in the latest C++ standard, main is still required to return an int. But both languages make a concession for the original dummy programmers: you can let execution "fall off" the end of main and the behavior is as if return 0; had been executed there. So this trivial program now has a successful termination status as of C99 and, I think, C++98 (or possibly earlier):

int main()
{
}

但是,两种语言都没有让第二代笨拙的程序员(以及其他所有阅读那些程序员在1980年代及以后编写的C书籍)的人让步.也就是说,void不是main的有效返回声明符(除非平台将其记录为已接受,并且仅适用于那些平台,而不适用于可移植语言).

But neither language makes a concession for the second-generation dumber programmers (and everyone else who read the C books that those programmers wrote in the 1980's and since). That is, void is not a valid return declarator for main (except where it is documented by platforms as being accepted, and that applies to those platforms only, not to the portable language).

哦,在C99中从C中删除了缺少的声明符的余量,因此main() { }在新的C语言中不再正确,并且不再是有效的C ++.顺带提及,C ++在其他地方确实具有这样的语法:即,要求类构造函数和析构函数不具有返回类型说明符.

Oh, and allowance for the missing declarator was removed from C in C99, so main() { } is no longer correct in new dialects of C, and isn't valid C++. Incidentally, C++ does have such a syntax elsewhere: namely, class constructors and destructors are required not to have a return type specifier.

好吧,现在大约是()(void).回想一下C ++引入了void.此外,尽管C ++引入了void,但没有引入(void)参数语法.更严格地类型化的C ++引入了原型声明,并消除了非原型函数的概念. C ++更改了() C语法的含义,使其可以声明.在C ++中,int func();声明一个不带参数的函数,而在C中,int func();则不做这样的事情:它声明一个我们不知道参数信息的函数.当C采用void时,委员会有一个丑陋的主意:为什么我们不使用语法(void)来声明不带参数的函数,然后()语法可以与松散的旧式行为保持向后兼容.顺应无类型编程.

Okay, now about () versus (void). Recall that C++ introduced void. Furthermore, though C++ introduced void, it did not introduce the (void) argument syntax. C++ being more rigidly typed introduced prototype declarations, and banished the concept of an unprototyped function. C++ changed the meaning of the () C syntax to give it the power to declare. In C++, int func(); declares a function with no arguments, whereas in C, int func(); doesn't do such a thing: it declares a function about which we do not know the argument information. When C adopted void, the committee had an ugly idea: why don't we use the syntax (void) to declare a function with no arguments and then the () syntax can stay backward compatible with the loosey-goosey legacy behavior pandering to typeless programming.

您可以猜测接下来发生的事情:C ++人员查看了此(void) hack,举起双手,将其复制到C ++中,以实现跨语言兼容性.事后看来,当您了解当今的语言差异并基本上不再关心这种程度的兼容性时,这是令人惊讶的.因此,在C和C ++中,(void)无疑意味着声明为没有参数".但是,在纯C ++从未打算成为C的C ++代码中使用它是丑陋且糟糕的样式:例如,在类成员函数上!编写class Foo { public: Foo(void); virtual ~Foo(void) /*...*/ };

You can guess what happened next: the C++ people looked at this (void) hack, threw up their arms and copied it into C++ for the sake of cross-language compatibility. Which in hindsight is amazing when you look at how the languages have diverged today and basically no longer care about compatibility to that extent. So (void) unambiguosly means "declare as having no arguments", in both C and C++. But using it in C++ code that is obviously pure C++ never intended to be C is ugly, and poor style: for instance, on class member functions! It doesn't make much sense to write things like class Foo { public: Foo(void); virtual ~Foo(void) /*...*/ };

当然,当您定义int main() { ... }这样的函数时,定义的函数不带参数,无论它使用哪种语言.区别在于引入了哪种声明信息范围.在C语言中,我们有一种荒谬的情况,就是可以在程序文本的同一单元中完全定义一个函数,而不声明它!

Of course, when you define a function like int main() { ... }, the function which is defined has no arguments, regardless of which language it is in. The difference is in what declaration info is introduced into the scope. In C we can have the absurd situation that a function can be fully defined, and yet not declared, in the same unit of program text!

当我们编写main时,通常不会在程序中调用它,因此它并不会定义定义所声明的内容. (在C ++中,不能从程序中调用main;在C中可以).因此,无论您使用C还是C ++,编写int main()还是int main(void)都无关紧要.调用main的东西看不到它的任何声明(无论如何,您是在程序中编写的).

When we write main, usually it is not called from within the program, and so it doesn't matter what the definition declares. (In C++, main must not be called from the program; in C it can be). So it is immaterial whether you write int main() or int main(void), regardless of whether you're using C or C++. The thing which calls main does not see any declaration of it (that you write in your program, anyway).

因此请记住,如果您写:

So just keep in mind that if you write:

int main()  /* rather than main(void) */
{ 
}

然后,尽管它是完美的C ++和正确的C语言,但由于C语言具有一点风格上的瑕疵:您正在编写一个旧的ANSI-C以前的函数,该函数不能用作原型.尽管对于main来说,在功能上并不重要,但是如果您以某种方式使用某些编译器,则可能会收到警告.例如,带有-Wstrict-prototypes选项的GCC:

then although it is perfect C++ and correct C, as C it has a slight stylistic blemish: you're writing an old-style pre-ANSI-C function that doesn't serve as a prototype. Though it doesn't functionally matter in the case of main, you may get a warning if you use some compilers in a certain way. For instance, GCC, with the -Wstrict-prototypes option:

test.c:1:5: warning: function declaration isn’t a prototype [-Wstrict-prototypes]

因为-Wstrict-prototypes是一个非常有用的警告,当使用C进行编程时会打开,以提高类型安全性(与-Wmissing-prototypes一起使用),并且我们努力从编译作业中消除警告,因此我们应该编写:

Because -Wstrict-prototypes is a darn useful warning to turn on when programming in C, for improved type safety, (along with -Wmissing-prototypes), and we strive to eliminate warnings from our compile jobs, it behooves us to write:

int main(void) /* modern C definition which prototypes the function */
{
}

这将使该诊断消失.

如果您希望main接受参数,则在int main(int argc, char **argv)中,参数名称由您决定.

If you want main to accept arguments, then it is int main(int argc, char **argv) where the parameter names are up to you.

在C ++中,您可以省略参数名称,因此可以使用此定义,它很好地代替了main().

In C++, you can omit parameter names, so this definition is possible, which serves nicely in the place of main().

int main(int, char **) // both arguments ignored: C++ only
{
}

由于参数向量是空指针终止的,因此您不需要argc,而C ++让我们无需引入未使用的变量即可表达这一点:

Since the argument vector is null-pointer-terminated, you don't need argc, and C++ lets us express that without introducing an unused variable:

#include <cstdio>

int main(int, char **argv)  // omitted param name: C++ only
{
  // dump the arguments
  while (*argv)
    std::puts(*argv++);
}

这篇关于之间的区别是什么:main(){},int main(){}和int main(void){}的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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