Cprogramming 简明教程

C - Main Function

main() Function in C

C 中的 main() 函数是任何程序的入口点。程序执行从 main() function 开始。它设计用于执行程序的主处理,并清理程序分配的任何资源。在 C 代码中,可能有任意数量的函数,但它必须有一个 main() function 。不考虑它在代码中的位置,它是第一个要执行的函数。

The main() function in C is an entry point of any program. The program execution starts with the main() function. It is designed to perform the main processing of the program and clean up any resources that were allocated by the program. In a C code, there may be any number of functions, but it must have a main() function. Irrespective of its place in the code, it is the first function to be executed.

Syntax

以下是 C languagemain() 函数的语法 −

The following is the syntax of the main() function in C language

int main(){
   //one or more statements;
   return 0;
}

Syntax Explained

作为其语法的一部分,函数具有遵循形成标识符规则(以字母或下划线开头,并带有字母、数字或下划线)的名称。名称后面是括号。通常,main() 函数不带任何参数定义,但它可能具有 argv 和 argv 参数来从命令行接收值。

As a part of its syntax, a function has a name that follows the rules of forming an identifier (starting with an alphabet or underscore and having alphabet, digit or underscore). The name is followed by a parenthesis. Typically, the main() function is defined with no arguments, although it may have argv and argv argument to receive values from the command line.

Valid/Different Signatures of main() Function

main() 函数的签名(原型)是 −

The signatures (prototype) of a main() function are −

int main() {
   . .
   return 0;
}

Or

int main(void){
   . .
   return 0;
}

Or

int main(int argc, char *argv[]){
   . .
   return 0;
}

Example of main() Function

以下示例演示了 main() 函数:

The following example demonstrates the main() function:

#include <stdio.h>

int main() {
  // Write code from here
  printf("Hello World");
  return 0;
}

Important Points about main() Function

  1. A C program must have a main() function.

  2. The main is not a C keyword. It is classified as a user-defined function because its body is not pre−decided, it depends on the processing logic of the program. By convention, int is the return type of main(). The last statement in the function body of main() returns 0, to indicate that the function has been successfully executed. Any non−zero return value indicates failure.

  3. Some old C compilers let you define main() function with void return type.

  4. However, this is considered to be non−standard and is not recommended.

  5. As compared to other functions, the main() function: Can’t be declared as inline.Can’t be declared as static.Can’t have its address taken.Can’t be called from your program.

How does main() Works in C?

程序执行从 main() 函数开始,因为它是程序的入口点,它会开始执行其内部编写的语句。源程序中的其他函数被定义用于执行确定的任务。main 函数可以调用其中任何一个函数。当 main 调用其他函数时,它会将执行控制传递给函数,选择性地传递必须数量和类型的参数,从而执行开始于被调用函数的第一个语句。当执行 return 语句或函数结束时,被调用函数将控制权返回给 main。注意,当其返回类型为 int 时,return 语句会作为最后一条语句隐式出现。

The program’s execution starts from the main() function as it is an entry point of the program, it starts executing the statements written inside it. Other functions within the source program are defined to perform certain task. The main function can call any of these functions. When main calls another function, it passes execution control to the function, optionally passing the requisite number and type of arguments, so that execution begins at the first statement in the called function. The called function returns control to main when a return statement is executed or when the end of the function is reached. Note that return statement is implicitly present as the last statement when its return type is int.

程序通常会在从 main 返回或到达其末尾时停止执行,尽管它可能由于种种原因在程序的其他部分终止。例如,您可能想要在检测到某些错误条件时强制终止程序。为此,可以使用 exit 函数。

A program usually stops executing when it returns from or reaches the end of main, although it can terminate at other points in the program for various reasons. For example, you may want to force the termination of your program when some error condition is detected. To do so, you can use the exit function.

Use of exit() in main() Function

C exit() function 是一个用于终止调用进程的标准库函数。使用 exit(0) 表示没有错误,使用 exit(1) 表示程序因遇到的错误而退出。

The C exit() function is a standard library function used to terminate the calling process. Use exit(0) to indicate no error, and exit(1) to indicate that the program is exiting with because of an error encountered.

Example

#include <stdio.h>
#include <stdlib.h>

int add(int, int);

int main (){
   int i;
   for ( i = 1; i<=5; i++){

      if ( i == 3 ){
         printf  (" \n exiting ..");
         exit(0);
      }
      else

      printf  (" \n Number is %d", i);
   }

   return 0;
}
Number is 1
Number is 2
exiting ..

Command-line Arguments with main()

通常, main() 函数被定义为没有参数。不过,可以通过参数定义 main() 来使其接受来自命令行中的值。在此类用法中,main() 函数定义如下所述:

Typically, the main() function is defined without any arguments. However, you may define main() with arguments to let it accept the values from the command line. In this type of usage, main() function is defined as follows −

Syntax

以下是用 command-line arguments 的 main() 函数的语法:

The following is the syntax of main() function with command-line arguments:

int main(int argc, char *argv[]){
   . .
   return 0;
}

Argument Definitions

参数定义如下:

The argument definitions are as follows −

*argc * - 第一个参数是整数,包含 argv 中紧随其后的参数计数。argc 参数始终大于或等于 1。

*argc * − The first argument is an integer that contains the count of arguments that follow in argv. The argc parameter is always greater than or equal to 1.

argv - 第二个参数是表示程序用户输入的命令行参数的以 null 结尾的字符串数组。约定上,argv[0] 是用来调用程序的命令。argv[1] 是第一个命令行参数。来自命令行的最后一个参数是 argv[argc - 1],而 argv[argc] 始终为 NULL。

argv − The second argument is an array of null−terminated strings representing command-line arguments entered by the user of the program. By convention, argv[0] is the command with which the program is invoked. argv[1] is the first command−line argument. The last argument from the command line is argv[argc − 1], and argv[argc] is always NULL.

Example: Using main() Function with Command-line Arguments

考虑以下程序以理解命令行参数。

Consider the following program to understand command−line arguments.

#include <stdio.h>
#include <stdlib.h>

int add(int, int);

int main (int argc, char *argv[]){
   int x, y, z;

   if (argc<3){
      printf("insufficient arguments");
   }
   else{
      x = atoi(argv[1]);
      y = atoi(argv[2]);
      z = x+y;
      printf("addition : %d", z);
   }
   return 0;
}

只需编译并构建程序为 test.c,不要在您进行编辑和编译的 IDE 中运行。转到命令提示符并按如下方式运行程序:

Just compile and build the program as test.c, don’t run from the IDE in which you have edited and compiled. Go to the command prompt and run the program as follows −

C:\Users\mlath>test 10 20
addition : 30

在本章中,我们学习了在 C 中定义 main() 函数的重要性及语法。任何 C 程序都必须有 main() 函数。按照惯例,它应该返回 0 以表示执行成功。您还可以为 main() 函数定义参数,它们可以从命令行中传递。

In this chapter, we learned the importance and syntax of defining a main() function in C. Any C program must have a main() function. As a convention it should return 0 to indicate successful execution. You can also define arguments to a main() function, they can be passed from the command−line.