What is the main function used for? Main function arguments

When creating a console application in the C++ programming language, a line very similar to this is automatically created:

Int main(int argc, char* argv) // main() function parameters

This line is the header main function main() , the parameters argс and argv are declared in parentheses. So, if the program is launched via command line, then it is possible to pass some information to this program; this is why the argc and argv parameters exist. The argc parameter has an int data type, and contains the number of parameters passed to the main function. Moreover, argc is always at least 1, even when we do not pass any information, since the first parameter is the name of the function. The argv parameter is an array of pointers to strings. Only string data can be passed through the command line. Pointers and strings are two large topics for which separate sections have been created. So it is through the argv parameter that any information is transmitted. Let's develop a program that we will launch through the command line Windows string, and give her some information.

// argc_argv.cpp: Defines the entry point for the console application. #include "stdafx.h" #include using namespace std; int main(int argc, char* argv) ( if (argc ><< argv<

// code Code::Blocks

// Dev-C++ code

// argc_argv.cpp: Defines the entry point for the console application. #include using namespace std; int main(int argc, char* argv) ( if (argc > 1) // if we pass arguments, then argc will be greater than 1 (depending on the number of arguments) ( cout<< argv<

After we have debugged the program, open the Windows command line and drag the executable file of our program into the command line window. The full path to the program will be displayed in the command line (but you can enter the path to the program manually), after which you can click ENTER and the program will start (see Figure 1).

Figure 1 - Main function parameters

Since we simply ran the program and did not pass any arguments to it, the Not arguments message appeared. Figure 2 shows the launch of the same program via the command line, but passing it the Open argument.

Figure 2 - Main function parameters

The argument is the word Open, as can be seen from the figure, this word appeared on the screen. You can pass several parameters at once, separating them with a comma. If you need to pass a parameter consisting of several words, then they must be enclosed in double quotes, and then these words will be considered as one parameter. For example, the figure shows the launch of a program, passing it an argument consisting of two words - It work.

Figure 3 - Main function parameters

And if you remove the quotes. Then we will see only the word It. If you do not plan to pass any information when running the program, you can remove the arguments in the main() function, and you can also change the names of these arguments. Sometimes modifications to the argc and argv parameters are encountered, but this all depends on the type of application being created or on the development environment.

I know the thread is old, but this question was bothering me a few years ago, so I wanted to throw in my half a percent (if that).

I always treat C functions as if they fix the number of arguments regardless of context, unless they use va_args. That is, I believe that they ALWAYS have a prototype:

Int main(int argc, char **argv).

even if no arguments are passed, the function has those arguments on the stack because the main function does not have function overloading.

C has the ability to have primitive overloading by simply pretending that the argument is missing. In this case, the argument is still passed and is on the stack, but you never access it, so it just reduces the size of the source code.

Saying int main() simply means that I know the function can have parameters, but I don't use them, so I write int main().

The statement int main (void) says that main SCENELY has no arguments and implies that there are two different function prototypes:

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

Since C doesn't have an overload function, this is somewhat misleading to me and I don't trust code with a void in it. I wouldn't unless main NEVER accepted any parameters, in which case main(void) would be completely fine.

NOTE. Some implementations have more parameters in the main than argc and argv like env, but that doesn't bother me because I know I'm not saying directly that these are only two parameters, but these are the minimum parameters and everything is fine to have more, but not less. This contradicts the direct statement of int main(void), which screams at me as THIS FUNCTION HAS NO PARAMETERS, which is not true, since it is, they are simply omitted.

Here's my basic code:

/* sample.c - build into sample. */ #include int main(void) ( int _argc = *((int *)2686800); char ***_pargv = (char ***)2686804; int i; for (i = 1; i< _argc; ++i) { printf("%s ", (*_pargv)[i]); } return 0; }

./sample I clearly have arguments

The function clearly has arguments passed to it, even though it doesn't explicitly say that it doesn't type void into the function prototype.

As mentioned above:

(6.7.6.3p10) A special case of an unnamed parameter of type void as soon as an element in the list indicates that the function has no parameters.

So saying that a function has void as an argument but actually having arguments on the stack is a contradiction.

My point is that the arguments still exist, so explicitly saying that main contains no arguments is dishonest. A fair way would be to say int main(), which doesn't assert anything about how many parameters it has, only how many parameters you need.

NOTE2: _argc, _pargv are system dependent to find your values ​​you should find by running this program:

/* findargs.c */ #include int main(int argc, char **argv) ( printf("address of argc is %u.\n", &argc); printf("address of argv is %u.\n", &argv); return 0; )

These values ​​should remain correct for your specific system.

What are functions for in C?

Functions in C are used to perform specific actions within a general program. The programmer himself decides which actions to display in functions. It is especially convenient to use functions for repetitive actions.

A simple example of a function in C

Example of a function in C:

#include #include int main(void) ( puts("Functions in C"); return EXIT_SUCCESS; )

This is a very simple C program. It simply prints the line "Functions in C". The program has a single function called main. Let's look at this function in detail. In the function header, i.e. in line

int is the return type of the function;

main is the name of the function;

(void) is a list of function arguments. The word void indicates that the function has no arguments;

return is a statement that terminates the execution of a function and returns the result of the function to the point at which the function was called;

EXIT_SUCCESS is a value equal to zero. It is defined in the stdlib.h file;

part of the function after the header, enclosed in curly braces

{
puts("Functions in C");
return EXIT_SUCCESS;
}

called the body of the function.

So, when we work with a function, we need to indicate the name of the function, for us it is main, the type of the value returned by the function, for us it is int, give a list of arguments in parentheses after the name of the function, we have no arguments, so we write void, execute in the body of the function some actions (for the sake of which the function was created) and return the result of the function using the return statement. Here's the basics you need to know about functions in C.

How to call another function from one function in C?

Let's look at an example of calling functions in C:

/* Author: @author Subbotin B.P..h> #include int main(void) ( puts("Functions in C"); int d = 1; int e = 2; int f = sum(d, e); printf("1 + 2 = %d", f); return EXIT_SUCCESS; )

We run it and get:

This example creates a sum function that adds two integers and returns the result. Let's look at the structure of this function in detail.

sum function header:

int sum(int a, int b)

here int is the return type of the function;

sum is the name of the function;

(int a, int b) - in parentheses after the function name there is a list of its arguments: the first argument is int a, the second argument is int b. The argument names are formal, i.e. When calling a function, we are not required to send the values ​​of variables named a and b as arguments to this function. In the main function we call the sum function like this: sum(d, e);. But it is important that the arguments passed to the function match the type declared in the function.

In the body of the sum function, i.e. Inside the curly braces after the function header, we create a local variable int c, assign it the value of the sum of a plus b, and return it as the result of the function with the return statement.

Now let's see how the sum function is called from the main function.

Here is the main function:

Int main(void) ( puts("Functions in C"); int d = 1; int e = 2; int f = sum(d, e); printf("1 + 2 = %d", f); return EXIT_SUCCESS; )

First we create two int variables

Int d = 1; int e = 2;

We will pass them to the sum function as argument values.

int f = sum(d, e);

its value will be the result of the sum function, i.e. we call the sum function, which will return an int value, which we assign to the variable f. We pass d and f as arguments. But in the function header sum

int sum(int a, int b)

the arguments are called a and b, why then do we pass d and f? Because formal arguments are written in the function header, i.e. The names of the arguments are NOT important, but their types are important. The sum function has both arguments of type int, which means that when calling this function, you must pass two arguments of type int with any names.

One more subtlety. A function must be declared before it is first called. In our example, this is what happened: first the sum function is declared, and then we call it from the main function. If a function is declared after the place where it is called, then a function prototype should be used.

Function prototype in C

Let's look at an example of a function in C:

/* Author: @author Subbotin B.P..h> #include int sum(int a, int b); int main(void) ( puts("Functions in C"); int d = 1; int e = 2; int f = sum(d, e); printf("1 + 2 = %d", f); return EXIT_SUCCESS; ) int sum(int a, int b) ( int c = 0; c = a + b; return c; )

In this example, the sum function is defined below where it is called in the main function. In this case, you need to use the sum function prototype. Our prototype is declared above the main function:

int sum(int a, int b);

A prototype is a function header that ends with a semicolon. A prototype is a declaration of a function that will be defined below. This is exactly what we did: we declared a function prototype

int f = sum(d, e);

and below the main function we define the sum function, which was previously declared in the prototype:

Int sum(int a, int b) ( int c = 0; c = a + b; return c; )

How is a function declaration in C different from a function definition in C?

When we write a function prototype, for example like this:

int sum(int a, int b);

then we declare a function.

And when we implement a function, i.e. We write down not only the title, but also the body of the function, for example:

Int sum(int a, int b) ( int c = 0; c = a + b; return c; )

then we define a function.

return statement

The return statement terminates a function in C and returns the result of its operation to the point of call. Example:

Int sum(int a, int b) ( int c = 0; c = a + b; return c; )

This function can be simplified:

Int sum(int a, int b) ( return a + b; )

here the return statement will return the value of the sum a + b.

There can be several return statements in one function. Example:

Int sum(int a, int b) ( if(a > 2) ( return 0;// First case; ) if(b< 0) { return 0;// Второй случай; } return a + b; }

If in the example the value of argument a is greater than two, then the function will return zero (the first case) and everything below the comment “// First case;” will not be executed. If a is less than two, but b is less than zero, then the function will complete its work and everything below the comment “// Second case;” will not be executed.

And only if both previous conditions are not met, then program execution will reach the last return statement and the sum a + b will be returned.

Passing function arguments by value

Arguments can be passed to a C function by value. Example:

/* Author: @author Subbotin B.P..h> #include int sum(int a) ( return a += 5; ) int main(void) ( puts("Functions in C"); int d = 10; printf("sum = %d\n", sum(d)) ; printf("d = %d", d); return EXIT_SUCCESS; )

In the example, in the main function, we create a variable int d = 10. We pass this variable by value to the sum(d) function. Inside the sum function, the value of the variable is increased by 5. But in the main function, the value of d will not change, because it was passed by value. This means that the value of the variable was passed, not the variable itself. This is evidenced by the result of the program:

those. after returning from the sum function, the value of d did not change, whereas inside the sum function it did change.

Passing C function pointers

If you pass a pointer to this variable as an argument to a function instead of the value of a variable, then the value of this variable can change. For example, we take the program from the previous section, changing it slightly:

/* Author: @author Subbotin B.P..h> #include int sum(int *a) ( return *a += 5; ) int main(void) ( puts("Functions in C"); int d = 10; printf("sum = %d\n", sum(&d )); printf("d = %d", d); return EXIT_SUCCESS; )

In this version of the program, I switched from passing an argument by value to passing a pointer to a variable. Let's take a closer look at this point.

printf("sum = %d\n", sum(&d));

What is passed to the sum function is not the value of the variable d, equal to 10, but the address of this variable, like this:

Now let's look at the sum function:

Int sum(int *a) ( return *a += 5; )

Its argument is a pointer to int. We know that a pointer is a variable whose value is the address of some object. The address of the variable d is sent to the sum function:

Inside sum, the pointer int *a is dereferenced. This allows us to move from the pointer to the variable itself, to which our pointer points. And in our case this is the variable d, i.e. expression

is equivalent to the expression

Result: the sum function changes the value of the variable d:

This time the value of d changes after returning from sum, which was not observed in the previous paragraph when we passed the argument by value.

C/C++ in Eclipse

I made all the examples for this article in Eclipse. You can see how to work with C/C++ in Eclipse. If you work in a different environment, the examples will work there too.

The basic form of writing a function is as follows

return_type function_name(parameter_list) { body_function) The type of data returned by the function is specified using the element return_type . Below the element parameter_list implies a comma-separated list of variables that can take any arguments passed by the function.

In C89, if the data type returned by a function is not explicitly specified, then the type int is assumed. In C++ and C99, the default int type is not supported, although most C++ compilers still make this assumption.

Function prototypes

In the C++ language, all functions must have prototypes, and in the C language, prototypes are formally optional, but highly desirable. The general form of a prototype definition is as follows.

return_type function_name(parameter_list); For example. float fn(float x); //or float fn(float);

In C, the void keyword is used instead of a parameter list to specify the prototype of a function that has no parameters. In C++, an empty parameter list in a function prototype means that the function has no parameters. The word void is optional in this case.

Returning values ​​(return statement)

Returning values ​​in functions is done using the return statement. it has two notation forms.

Return; return meaning;

In C99 and C++, a form of the return statement that does not specify a return value should only be used in void functions.

Function Overloading

In C++, functions can overload. When a function is said to be overloaded, it means that two or more functions have the same name, but each version of the overloaded function has a different number or type of parameters. Consider an example of the following three overloaded functions.

Void func (int a)( cout

In each case, the type and number of arguments are analyzed to determine which version of func() will be called.

Passing Default Function Arguments

In C++, a function parameter can be assigned a default value, which will be automatically used if the corresponding argument is not specified when calling the function. For example.

Void func (int a = 0, int b = 10)() //call func(); func(-1); func(-1, 99);

Scope and lifetime of variables.

The C and C++ languages ​​define visibility rules that establish concepts such as the scope and lifetime of objects. There is a global scope and a local one.

Global a scope exists outside of all other scopes. A name declared in the global scope is known to the entire program. For example, a global variable is available for use by all program functions. Global variables exist throughout the life cycle of a program.

Local the scope is determined by the boundaries of the block. A name declared within a local scope is known only within that scope. Local variables are created when entering a block and destroyed when exiting it. This means that local variables do not store their values ​​between function calls. To preserve variable values ​​between calls, you can use the static modifier.

Recursion

In C and C++, functions can call themselves. This process is called recursion, and a function that calls itself is recursive. As an example, let's use the fact() function, which calculates the factorial of an integer.

Int fact (int n) ( int ans; if (n == 1) return 1; ans = fact (n-1) * n; return ans; )

main() function

Execution of a C/C++ program begins with the execution of the main() function. (Windows programs call the WinMain() function);

The main() function has no prototype. Therefore, various forms of the main() function can be used. The following variants of the main() function are valid for both C and C++.

Int main(); int main(int argc, char *argv)

As can be seen from the second form of recording, f. main() accepts at least two parameters. They are called argc and argv. These arguments will store the number of command line arguments and a pointer to them respectively. argc is an integer type and its value will always be at least 1 because, as in C and C++, the first argument is always the name of the program. The argv parameter must be declared as an array of character pointers, with each element pointing to a command line argument. Below is an example program that demonstrates the use of these arguments.

#include using namespace std; int main (int argc, char *argv) ( if (argc

Passing pointers

Although the C and C++ languages ​​use parameter passing by value by default, you can manually construct a call to f. with passing parameters by reference. To do this, you need to pass a pointer to the argument. Since in this case the function is passed the address of the argument, It turns out that it is possible to change the value of the argument outside the function. For example.

Void swap (int *x, int *y) ( int temp; temp = *x; ​​*x = *y; *y = temp; ) //call swap (&a, &b);

In C++, the address of a variable can be passed to a function automatically. This is implemented using reference-parameter. When using a reference parameter, the address of the argument is passed to the function, and the function operates on the argument rather than on a copy. To create a link parameter, you must precede its name with an ampersand (&). Inside f. this parameter can be used normally, without using the asterisk (*) operator, for example.

Void swap (int &x, int &y)( int temp; temp = x; x = y; y = temp; ) //call swap (a, b);

Function specifiers

C++ defines three function specifiers:

  • inline
  • virtual
  • explicit

The inline specifier is a request to the compiler: instead of creating a function call, expand its code directly on the line. If the compiler cannot insert a function into a string, it has the right to ignore this requirement. The inline specifier can define both member functions and non-member functions.

As a virtual function (using the virtual specifier) ​​f. is defined in the base class and overridden in the derived class. Using virtual functions as an example, you can understand how the C++ language supports polymorphism.

The explicit specifier only applies to constructors. A constructor defined as explicit will only be used if the initialization exactly matches what is specified by the constructor. No conversions will be performed (ie the explicit specifier creates a "non-converting constructor").

Function Templates

The general form of defining a template function is as follows.

Tetemplate type> return_type function_name (parameter_list) ( //function body ) Here type means a placeholder label for the type of data that this function will actually deal with. In the template statement, you can define multiple data type parameters using the form of a comma-separated list of elements.

Let's look at an example.

Template void swap (X &a, X &b) ( X temp; temp = a; a = b; b = temp; ) //call int a, b; float x, y; swap(a, b); swap(x, y);

Function pointers

You can create a pointer to a function, like to any other C language object. The syntax is as follows.

return_type (*index_name)(variable_description); This declaration creates a pointer to a function called index_name , which contains variables variable_description and which returns a value of type return_type .

A function can be called using a pointer as follows.

index_name = function_name; variable = index_name (variables); Here the first line creates a function reference function_name. The second line actually calls the function through the pointer index_name , to which variables are passed variables, the value is returned to a variable variable .

The following example demonstrates the creation of a pointer and two ways to call a function through a pointer, as well as passing the function as a parameter to other functions.

Double y; double (*p)(doublr x); p=sin; //creating a pointer to the function sin() y = (*p)(2.5); //call y = p(2.5); //call //passing the function as a parameter double y; double f(double (*c)(double x), double y)( return c(y); //call the passed function to pointer c and return the value ) y = f(sin, 2.5); //pass the function f to the function sin, as well as the parameter that will be processed

You can also create arrays of function pointers.

Int f1(void); int f2(void); int f3(void); int (*p)(void) = (f1, f2, f3) y = (*p)(); //function call f2 y = p(); //function call f3

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.

Internet