What does int main mean in c. Difference between int main() and int main(void)? Formal and actual parameters

Function main.

Every C and C++ program must have a main function; and it’s up to you where you place it. Some programmers place it at the beginning of the file, some at the end. However, regardless of its position, you need to remember the following: Arguments to the "main" function. The Borland C++ starting procedure sends three parameters (arguments) to the main function: argc, argv and env. - argc, an integer, is the number of command line arguments sent to the main function, - argv is an array of pointers to strings (char *). Under DOS 3.x and later, argv is defined as the full path of the program to be launched. When running under earlier versions of DOS, argv points to a null string (""). argv points to the first command line line after the program name. argv points to the second command line line after the program name. argv points to the last argument sent to main. argv contains NULL. - env ​​is also an array of pointers to strings. Each env element contains a string of the form ENVVAR=value. ENVVAR is the name of an environment variable, such as PATH or 87.<значение>this is the value of a given environment variable, for example C:\DOS;C:\TOOLS (for PATH) or YES (for 87). Note, however, that if you specify some of these arguments, you must specify them in this order: argc, argv, env. For example, the following argument declarations are valid: main() main(int argc) /* valid but not very good */ main(int argc, char *argv) main(int argc, char *argv, char *env) Main(int) declaration argc) is not very convenient because knowing the number of parameters, you do not have access to them yourself. The env argument is always accessible through the environ global variable. See the environ variable (in Chapter 3) and the putenv and getenv functions (in Chapter 2). The argc and argv parameters are also available through the _argc and _argv variables. Example program using argc, argv and env. This is an example program, ARGS.EXE, which demonstrates the simplest way to use the arguments passed to the main function. /* ARGS.C program */ #include #include void main(int argc, char *argv, char *env) ( int i; printf("The value of argc is %d \n\n",argc); printf("The command line contains %d parameters \n\n" ,argc); for (i=0; i<=argc; i++) printf(" argv[%d]: %s\n",i,argv[i]); printf("Среда содержит следующие строки:\n"); for (i=0; env[i] != NULL; i++) printf(" env[%d]: %s\n",i,env[i]); return 0; } Предположим, что вы запускаете программу ARGS.EXE со следующей командной строкой: C:> args first_arg "arg with blanks" 3 4 "last but one" stop! Note that you can send an argument with blanks by enclosing it in double quotes, as shown in the "argument with blanks" and "last but one" example in the program call. As a result of running the program, you will get something like the following: The value of argc is 7 The command line contains 7 parameters argv: c:\turboc\testargs.exe argv: first_arg argv: arg with blank argv: 3 argv: 4 argv: last but one argv: stop! The environment contains the following lines: env: COMSPEC=C:\COMMAND.COM env: PROMPT=$p $g env: PATH=C:\SPRINT;C:\DOS;C:\BC Maximum total length of the command line sent to the main function (including spaces and the name of the program itself), cannot exceed 128 characters; These are DOS limitations. Command Line Escape Characters Command line arguments can contain escape characters. However, they can expand for all file names that match the argument in the same way as is done, for example, with the DOS copy command. To use escape symbols, when linking your program with the linker, you must include the WILDARGS.OBJ object file that comes with Borland C++. If the WILDARGS.OBJ file is attached to your program, you can use arguments like "*.*" on the command line. In this case, the names of all files matching this mask are entered into the argv array. The maximum size of the argv array depends only on the size of the dynamic memory area. If no suitable files were found for a given mask, then the argument is passed in the form in which it was typed on the command line. (That is, the main function is passed a string containing escape characters). Arguments enclosed in double quotes ("...") are not expanded. Example. The following commands compile the ARGS.C file and link it to the WILDARGS.OBJ module, and then run the resulting ARGS.EXE program: bcc args wildarg.obj args C:\BORLANDC\INCLUDE\*.H "*.C" When running ARGS. EXE, the first argument expands to the names of all files with an H extension in the Borland C++ INCLUDE directory. Note that all lines include the full route (for example C:\TC\INCLUDE\ALLOC.H). The *.C argument is not expanded because it is enclosed in quotation marks. If you are working in an Integrated Environment (BC.EXE), then you simply need to specify in the project menu the name of the project file, which should contain the following lines: ARGS WILDARGS.OBJ Then, using the "Run/Arguments" commands, you should set the command line parameters. Comment. If you want escape character processing to always occur, i.e. In order for WILDARGS.OBJ to be automatically linked by the link editor, you must modify your standard C?.LIB library to include the file WILDARGS.OBJ. To do this, remove SETARGV from the library and add WILDARGS. This can be done with the following commands (we assume that the standard libraries and WILDARGS.OBJ are contained in the current directory): TLIB is described in Chapter 7, Utilities, of the User's Guide. tlib cs -setargv +wildargs tlib cc -setargv +wildargs tlib cm -setargv +wildargs tlib cl -setargv +wildargs tlib ch -setargv +wildargs Compiling using the -p switch (Pascal calling convention) If you compile your program using the Pascal calling convention (described in detail in Chapter 9 "Interfacing with assembly language", "Programmer's Guide"), you must remember that the main function must be explicitly declared as a C function. This can be done using keyword cdecl is something like this: cdecl main(int argc, char *argv, char *env) The value returned by the main function. The main function returns a value that is the program's exit code: this is an integer. However, if your program uses the exit (or _exit) function to exit, then the return value will be the argument of that function. For example, if your program contains a call: exit(1) then the exit code will be 1. If you use the Borland C++ integrated environment (BC.EXE) to run the program, then you can view the return value of the main function by selecting "File | Get Info ".

Page 53 of 85

1.5.3. Passing parameters to the main function

The main function, which begins the execution of a C program, can be defined with parameters that are passed from the external environment, for example, from the command line. The external environment has its own rules for data representation, or rather, all data is presented in the form of character strings. To pass these strings to the main function, two parameters are used, the first parameter is used to transmit the number of strings to be transmitted, the second is used to transmit the strings themselves. The common (but not required) names for these parameters are argc and argv. The argc parameter is of type int, its value is formed from analysis of the command line and is equal to the number of words on the command line, including the name of the called program (a word is any text that does not contain a space character). The argv parameter is an array of pointers to strings, each containing one word from the command line. If a word must contain a space character, it must be enclosed in quotation marks when writing it to the command line.

The main function can also have a third parameter, which is usually called argp, and which serves to transfer to the main function the parameters of the operating system (environment) in which the program is executed in the C programming language.

The main function header looks like this:

If, for example, the command line of a program in the C programming language looks like:

A:\>cprog working "C program" 1

then the arguments argc, argv, argp are represented in memory as shown in the diagram in Fig. 1.

Argc[4]
argv --> -->
-->
-->
-->
argp --> -->
-->
-->
-->
Fig.1. Command line options layout

The operating system supports passing values ​​for the parameters argc, argv, argp, and it is the user's responsibility to pass and use the actual arguments to the main function.

The following example is a program that prints the actual arguments passed to the main function from the operating system and operating system parameters.

Example:
int main (int argc, char *argv, char *argp)
( int i=0;
printf("\nProgram name %s", argv);
for (i=1; i>=argc; i++)
printf("\n argument %d is %s", argv[i]);
printf("\nOperating system settings:");
while (*argp)
( printf ("\n %s",*argp);
argp++;
}
return(0);
}

Operating system parameters can also be accessed using the geteuv library function; its prototype looks like this:

char *geteuv (const char *varname);

The argument to this function specifies the name of the environment parameter, a pointer to the value of which will be returned by the geteuv function. If the specified parameter is not currently defined in the environment, the return value is NULL.

Using the pointer obtained by the geteuv function, you can only read the value of the operating system parameter, but cannot change it. The puteuv function is used to change the value of a system parameter.

The C programming language compiler constructs a C program in such a way that some initialization is performed at the beginning of the program, including, among other things, processing the arguments passed to the main function and passing it the values ​​of environment parameters. These actions are performed by the library functions _setargv and _seteuv, which are always placed before the main function by the compiler.

If a program in the C programming language does not use the passing of arguments and values ​​of operating system parameters, then it is advisable to prohibit the use of the library functions _setargv and _seteuv by placing in the C program in the programming language, before the main function, functions with the same names, but which do not perform any actions (stubs). The beginning of the program in this case will look like:

setargv()
}
-seteuv()
( return ; /* empty function */
}
int main()
( /* main function without arguments */
...
...
renurn(0);
}

In the above program, when calling the library functions _setargv and _seteuv, functions placed in the program by the user will be used and will not perform any actions. This will significantly reduce the size of the resulting exe file.

Borland C++ supports three arguments to main(). The first two are the traditional argc and argv. These are the only arguments to main() defined by the ANSI C standard. They allow command line arguments to be passed to the program. Command line arguments are the information that follows the program name on the operating system command line. For example, when a program is compiled using the Borland line compiler, it is typically typed bcc program_name

Where program_name is a program that needs to be compiled. The program name is passed to the compiler as an argument.

The argc parameter contains the number of command line arguments and is an integer. It is always equal to at least 1, since the program name qualifies as the first argument. The argv parameter is a pointer to an array of character pointers. Each element of this array points to a command line argument. All command line arguments are strings. All numbers are converted by the program into internal format. The following program prints "Hello" followed by the username when typed directly after the program name:

#include

{
if(argc!=2)
{
printf("You forgot to type your name\n");
return 1;
}
printf("Hello %s", argv);
return 0;
}

If you call this program name, and the user name is Sergey, then to start the program you should type:
name Sergey.
As a result of the program the following will appear:
"Hello Sergey."

Command line arguments must be separated by spaces or tabs. Commas, semicolons, and similar characters are not considered delimiters. For example:

Consists of three lines, while

Herb,Rick,Fred

This is one line - commas are not delimiters.

If you need to pass a string containing spaces or tabs as a single argument, you must enclose it in double quotes. For example, this is one argument:

"this is a test"

It is important to declare argv correctly. The most typical method is:

Empty parentheses indicate that the array does not have a fixed length. You can access individual elements using argv indexing. For example, argv points to the first line, which always contains the program name. argv points to the next line and so on.

Below is a small example of using command line arguments. It counts down from the value specified on the command line and emits a signal when it reaches zero. Note that the first argument contains a number converted to an integer using the standard atoi() function. If the string "display" is present as the second argument, then the counter itself will be displayed on the screen.

/* counting program */

#include
#include
#include
int main(int argc, char *argv)
{
int disp, count;
if(argc<2)
{
printf("You must enter the length of the count\n");
printf("on the command line. Try again.\n");
return 1;
}
if (argc==3 && !strcmp(argv,"display")) disp = 1;
else disp = 0;
for(count=atoi(argv); count; -count)
if (disp) printf("%d ", count);
printf("%c", "\a"); /* on most computers this is a call */
return 0;
}

Please note that if no arguments are specified, an error message appears. This is most typical for programs that use command line arguments to issue instructions if an attempt was made to run the program without the correct information.

To access individual command line characters, add a second index to argv. For example, the following program prints out all the arguments it was called with, one character at a time:

#include
int main(int argc, char *argv)
{
int t, i;
for(t=0; t {
i = 0;
while(argv[t][i])
{
printf("%c", argv[t][i]);
}
printf(" ");
}
return 0;
}

We must remember that the first index is for accessing a string, and the second is for accessing a character in a string.

Typically argc and argv are used to obtain source commands. It is theoretically possible to have up to 32767 arguments, but most operating systems don't even allow you to get close to that. Typically these arguments are used to specify a file name or options. Using command line arguments gives the program a professional look and allows the program to be used in batch files.

If you include the WILDARGS.OBJ file supplied with Borland C++, you can use templates in *.EXE type arguments. (Borland C++ automatically handles wildcards and increments argc accordingly.) For example, if you connect WILDARGS.OBJ to the following program, it will tell you how many files match the filename specified on the command line:

/* Link this program with WILDARGS.OBJ */

#include
int main(int argc, char *argv)
{
register int i;
printf("%d files match specified name\n", argc-1);
printf("They are: ");
for(i=1; i printf("%s ", argv[i]);
return 0;
}

If we call this program WA, then run it as follows, we will get the number of files with the EXE extension and a list of the names of these files:

In addition to argc and argv, Borland C++ also provides a third command line argument -env. The env parameter allows a program to access information about the operating system environment. The env parameter must follow argc and argv and is declared as follows:

As you can see, env is declared in the same way as argv. Just like argv, it is a pointer to an array of strings. Each line is an environment string defined by the operating system. The env parameter has no equivalent argc parameter that tells how many environment rows there are. Instead, the last line of the environment is null. The following program prints all the environment strings currently defined in the operating system:

/* this program displays all the environment lines */

#include
int main(int argc, char *argv, char *env)
{
int t;
for(t=0; env[t]/ t++)
printf("%s\n", env[t]);
return 0;
}

Please note that although argc and argv are not used by the program, they must be present in the parameter list. C doesn't know the parameter names. Instead, their use is determined by the order in which the parameters are declared. In fact, you can call the parameter whatever you like. Since argc, argv, and env are traditional names, it is best to continue to use them so that anyone reading the program can instantly understand that these are arguments to the main() function.

A typical task for programs is to look up a value defined in an environment string. For example, the contents of the PATH line allow programs to use search paths. The following program demonstrates how to find strings that declare standard search paths. It uses the standard library function strstr(), which has the following prototype:

Char *strstr(const char *str1, const char *str2);

The strstr() function searches for the string pointed to by str1 in the string pointed to by str2. If such a string is found, a pointer to the first position is returned. If no matches are found, the function returns NULL.

/* the program searches among the environment strings for a line containing PATH */

#include
#include
int main (int argc, char *argv, char *env)
{
int t;
for(t=0; env[t]; t++)
{
if(strstr(env[t], "PATH"))
printf("%s\n", env[t]);
}
return 0;
}

Any C program begins with a call to the main() function. This function should be in every program.

Like any other function, the main() function can have parameters. Sometimes when starting a program it is useful to pass some information to it. This information is passed to main() using command line arguments. Command Line Arguments– this is information that is entered on the command line following the program name when the program is launched for execution outside of the program development environment. For example, to start archiving the task.cpp file, you need to type the following on the command line:

winrar a archTasktask.cpp // winrar.exe a archTasktask.cpp

where winrar is the name of the archiver program, and the lines “ a», « archTask" And " task. cpp» represents command line arguments that tell the program to create an archive (" a") With name archTask from one file task. cpp.

When passing parameters to the main() function, it must be defined like this:

int main(int argc, char *argv) ( ) // or void main(...)()

The argc parameter contains the number of arguments on the command line and is an integer, and it is always at least 1, because the first argument is always the program name (the program name with the full path to the program).

The argv parameter is a pointer to an array of pointers to strings. In this array, each element points to the next command line argument. Empty square brackets indicate that the array has an indefinite length. You can access individual arguments by indexing the argv array. For example, argv points to the first character string, which is always the program name; argv points to the first argument and so on. The argument list is limited to NULL, i.e. argv == NULL.

To access an individual character of one of the command line arguments, you must use the second index in argv. That is, the first index argv provides access to the string, and the second index provides access to its individual characters.

All command line arguments are strings, so the conversion of numeric parameters to the desired format must be provided in the program when it is developed.

An example of a program with different ways to convert numbers in symbolic format into integers and real numbers:

#include

#include

// at startup we set, for example, the following arguments: 100 2.7

void main(int a, char *b) (

k = strtol(b, &ptr, 10); // ptr = address of the error in the line

f = strtod(b, &ptr);

sscanf(b, "%d", &k);

sscanf(b, "%lf", &f);

The names argc and argv are traditional, but not required. These two parameters in the main() function can be called whatever you like.

A simple example of using command line arguments:

int main(int argc, char *argv) (

if (argc != 4) (

printf("Invalid program launch parameters!\n");

k = atoi(argv); // conversion of the number parameter

printf("Hello, %s from group %s of %d year",

If the name of the program is task, and your name is “Vasya”, group “PM-11” from the first year, then to start the program you should enter into the command line:

task Vasya PM-11 1

As a result of executing the program, the following message will appear on the screen: “Hello, Vasya from the 1st year PM-11 group.”

Please note that if not all command line arguments are supplied, an error message will be displayed. Programs that take command line arguments often do the following: When the user runs these programs without entering the required information, they display instructions on how to correctly specify the arguments.

Command line arguments must be separated by a space. If there are spaces in the argument itself, then to prevent it from making multiple arguments, this argument must be enclosed in double quotes. As a result, the entire quoted string will be considered one argument. For example, the program can be launched like this: task “Vasya and Petya” PM-21 2. As a result of executing the program, the message will appear on the screen: “Hello, Vasya and Petya from the 2nd year PM-21 group.”

What is char *argv? This an array whose elements are pointers, that is array of pointers. This means that when passing parameters to main(), it can be defined like this:

void main(int argc, char **argv) (

Task. Display all command line arguments (no need to display the program name).

#include

void main(int argc, char *argv)(

for (i = 1; i< argc; i++)

printf("%s\n", argv[i]);

Second option ================

#include

void main(int argc, char **argv)(

while((p=*argv) != NULL) (

printf("%s\n", p);

Typically, command line arguments are used to provide the program with initial data that it will need when it starts (for example, command line arguments often pass data such as the file name or program launch parameters).

When a program does not require command line parameters, the main() function uses the void keyword in its parameter list (or simply does not specify anything).

How to debug in B.C. programs that require command line arguments. In the menu Run→Arguments... you must enter command line arguments. There is no need to specify the program name. Then you can simply run and debug the program in the development environment as usual.

Please suspend AdBlock on this site.

So, why do we need custom functions? User-defined functions are needed to make it easier for programmers to write programs.

Remember, we talked about programming paradigms, more precisely about structured programming. The main idea there was that any program can be written using only three basic constructs: follow, condition and loop. Now we will add one more to these structures - “subroutines” - and get a new paradigm procedural programming".

The only difference is that we will write individual pieces of our main program (in particular, repeating ones) in the form of separate functions (subroutines, procedures) and call them as necessary. Essentially, the program will now describe the interaction of various functions.

So in this tutorial we will discuss in detail how functions are built internally. We'll also learn how to create our own custom functions.

How the functions work

Let's remember the information from the first lesson. All functions, including those written by the user, are arranged in a similar way. They have two main parts: the function header and the function body.

Listing 1.

Int main(void)( // function header // function body is written in curly braces)

Everything is clear with the body of the function: it describes the algorithm for the function. Let's look at the title. It consists of three mandatory parts:

  • return type;
  • function name;
  • function arguments.

First, the return type is written, for example, int , as in the main function. If a function should not return any value to the program, then the keyword void is written at this place. It would seem that since the function does not return anything, then there is no need to write anything. Previously, by the way, this was done in the C language, but then they added it for uniformity. Nowadays, modern compilers will issue warnings/errors if you don't specify a return type.
In some programming languages, functions that do not return any value are called procedures (for example, Pascal). Moreover, there are different syntaxes for creating functions and procedures. There is no such discrimination in the C language.

The function name is written after the return type. Well, after the name the types and number of arguments that are passed to the function are indicated.

Let's look at the headings of the functions we are already familiar with.

Listing 2.

// a function named srand that takes an integer returns nothing void srand(int) // a function named sqrt that takes a real float returns a float float sqrt(float) // a function named rand that takes no arguments, returns an integer int rand(void) //a function named pow that takes two arguments of type double, returns a real number of type double double pow(double, double)

How to create your own function

In order to create your own function, you need to fully describe it. The general rule applies here: before using it, declare and describe how it should work. To do this, let's return to the diagram of the structure of the program in the C language, which we had in the very first lesson. Let us mark on it the places where functions can be described.

Fig.1 Clarification of the program structure. Declaration of functions.

As you can see, there are two places where this can be done.

Let's look at an example that illustrates creating a custom function to calculate the maximum of two numbers.

Listing 3.

#include // declare a custom function named max_num // input: two integer parameters named a and b // output: the maximum of the two arguments int max_num(int a, int b)( int max = b; if (a > b) max = a; return max; ) //main program int main(void) ( int x = 0, y = 0; int m = 0; scanf("%d %d", &x, &y); m = max_num(x ,y); printf("max(%d,%d) = %d\n",x,y,m); return 0; )

Let me describe in detail how this program will work. The body of the main function is executed. The integer variables x, y and m are created. The variables x and y are read from the keyboard. Let's say we entered 3 5, then x = 3, y = 5. This should all be clear to you. Now the next line

Listing 4.

M = max_num(x,y);

The variable m must be assigned to what is to the right of the = sign. There we have the name of the function that we created ourselves. The computer looks for the declaration and description of this function. It is located above. According to this declaration, this function must accept two integer values. In our case, these are the values ​​​​written in the variables x and y. Those. numbers 3 and 5. Please note that it is not the variables x and y themselves that are passed to the function, but only the values ​​(two numbers) that are stored in them. What is actually passed to a function when it is called in a program is called the actual parameters of the function.

Now the max_num function starts executing. The first step is to create a separate temporary variable for each parameter described in the function header. In our case, two integer variables are created named a and b. These variables are assigned the values ​​of the actual parameters. The parameters themselves, described in the function header, are called formal parameters. So, the formal parameters a and b are assigned the values ​​of the actual parameters 3 and 5, respectively. Now a = 3, b = 5. Further inside the function we can work with these variables as if they were ordinary variables.

An integer variable named max is created and assigned the value b. Next, the condition a > b is checked. If it is true, then the value in the max variable should be replaced with a .

Next comes the return statement, which returns to the calling program (the main function) the value written in the max variable, i.e. 5 . After which the variables a, b and max are removed from memory. And we return to the line

Listing 5.

M = max_num(x,y);

The max_num function returned the value 5, which means that now there is 5 written to the right of the = sign. This value is written to the variable m. Then the line is displayed on the screen and the program ends.

Carefully read the last 4 paragraphs again to fully understand how the program works.

In the meantime, I’ll tell you why the lower block of function descriptions is needed. Imagine that you have written 20 small functions in your program. And all of them are described before the main function. It's not very convenient to get to the main program for so long. To solve this problem, functions can be described in a lower block.

But it will not be possible to simply transfer the entire function code there, because then the rule will be broken: before you use something, you must declare it. To avoid this problem, you need to use a function prototype.

The function prototype completely repeats the function header, followed by ; . Having specified the prototype in the upper block, in the lower one we can already fully describe the function. For the example above it might look like this:

Listing 6.

#include int max_num(int, int); int main(void) ( int x =0, y = 0; int m = 0; scanf("%d %d", &x, &y); m = max_num(x,y); printf("max(%d ,%d) = %d\n",x,y,m); return 0; ) int max_num(int a, int b)( int max = b; if (a > b) max = a; return max; )

Everything is very simple. Please note that the function prototype does not have to specify the names of the formal parameters; it is enough to simply indicate their types. In the example above, I did exactly that.