12

重複の可能性:
Cでパラメーターのない関数main()を定義する標準的な方法

次のようなCの関数の宣言定義を使用できますか?main()

int main() {}

はい、私はその標準が保証されたサポートされたバージョンが2つしかないことを示しているのを見ました:

int main(void) {}

int main(int argc, char* argv[]) {}

しかし、空のパラセはどうですか?C ++とは別の意味があることは知っていますが(Cでは、この関数のパラメーターの数とタイプが不明であることを意味します)、このmainの宣言定義を使用してCで非常に多くのコードを見ました。

では、誰が間違っているのでしょうか。

4

4 に答える 4

10

In C, there's a difference between the declarations int main(); and int main(void); (the former declares a function with an unspecified number of arguments, and the latter is actually called a proto­type). However, in the function definition, both main() and main(void) define a function that takes no arguments.

The other signature, main(int, char**), is an alternative form. Conforming implementations must accept either form, but may also accept other implementation-defined signatures for main(). Any given program may of course only contain one single function called main.

于 2012-08-27T17:31:30.947 に答える
3

int main()そして、このような他の関数宣言では、引数の数が不明であるため、これはメイン関数にとっては絶対に間違っています。int main(void)引数は取りません。

char* argv[]引数ベクトル です。_ コマンドラインで引数を書くと、この文字列のベクトルに引数が見つかります。時々あなたも見つけることができますchar **argvが、それは同じです。[]ユーザーからの引数の数がわからないため、括弧は空です。int argc 引数はこの目的のために存在します。これは、含まれている引数の数をカウントしますargvただし、リストは番兵値としても終了しますargv[argc] == NULL)。

ジェネリックとの違いについては、このリンクもお読みくださいfoo()foo(void)

于 2012-08-27T17:37:00.057 に答える
2

実装が(引数なしで)有効な署名として明示的に文書化する場合、int main()C99以降はすべて問題ありません(§5.1.2.2.1¶1、「...または他の実装定義の方法で」)。

実装がそれを文書化していないint main(void)場合、厳密に言えば、動作は定義されていません(§4¶2)が、私の経験では、 動作とは大幅に異なる動作につながる可能性はかなり低くなっています。

于 2012-08-27T17:44:19.500 に答える
1
   int main() {}
   this is the standard prior to the c99 standard of main method.

   int main(void){}
   this is the standard coined by ANSI.

   int main(int argc, char* argv[]) {}     
   This is the another version of main which provides the user to pass the command line
   argument to the main method.
于 2012-08-27T17:50:42.893 に答える