You get a bonus - 1 coin for daily activity. Now you have 1 coin

4. FUNCTIONS IN C

Lecture



General information

C programs usually consist of a large number of individual functions (subroutines). As a rule, these functions are small and can be located in one or several files. All functions are global. It is forbidden in a language to define one function within another. Communication between functions is carried out through arguments, return values ​​and external variables.

In general, functions in the C language must be declared. A function declaration (that is, a header description) must precede its use, and a function definition (that is, a full description) can be placed both after the program body (that is, the main () function) and before it. If a function is defined before the program body, as well as before its calls from the definitions of other functions, then the declaration may be absent. As already noted, the description of the function header is usually called the function prototype.

The function is declared as follows:

  type function_name (type parameter_1 type, type parameter_name_2, ...);  
 

The type of the function determines the type of value that the function returns. If the type is not specified, it is assumed that the function returns an integer value (int).

When you declare a function for each of its parameters, you can specify only its type (for example: type of function (int, float, ...), and you can give its name (for example: type of function (int a, float b, ...)) .

In C, it is allowed to create functions with a variable number of parameters. Then, when specifying a prototype, ellipsis is indicated instead of the last one.

The function definition is as follows:

  type function_name (type parameter_1 type, type parameter_name_2, ...) 
       { 
           function body 
       } 
 

Passing a value from the called function to the caller is done using the return statement, which is written as follows:

  return expression;  
 

There can be several such operators in a subroutine, and then they fix the corresponding exit points. For example:

  int f (int a, int b) 
       { 
           if (a> b) {printf ("max =% d \ n", a);  return a;  } 
           printf ("max =% d \ n", b);  return b; 
       } 
 

Call this function as follows:

  c = f (15, 5);   
       c = f (d, g);     
       f (d, g);         
 

The caller may, if necessary, ignore the return value. After the word return, you can not write anything; in this case, the calling function is not passed any value. The control is transferred to the calling function and in the case of exit "by the end" (the last closing brace).

In C, function arguments are passed by value, i.e. The called function receives its temporary copy of each argument, not its address. This means that the called function cannot change the value of the variable of the program that called it. However, this is easy to do if you pass to the function not variables, but their addresses. For example:

  void swap (int * a, int * b) 
       { 
           int * tmp = * a; 
      
           * a = * b; 
           * b = * tmp; 
       } 
 

Calling swap (& b, & c) (here the addresses of the variables b and c are passed to the subroutine) will cause the values ​​of b and c to swap places.

If the name of an array is used as an argument of a function, then only the address of the beginning of the array is passed, and the elements themselves are not copied. The function can change the elements of the array, moving (indexing) from its beginning.

Consider how functions can be passed an array as a parameter. Three options are possible here:

  1. The parameter is set as an array (for example: int m [100];).
  2. The parameter is set as an array without specifying its dimension (for example: int m [];).
  3. The parameter is set as a pointer (for example: int * m;). This option is used most often.

Regardless of the option chosen, the function is passed a pointer to the beginning of the array. The array elements themselves are not copied.

If some variables, constants, arrays, structures are declared as global, they should not be included in the parameter list of the called function.

  4. FUNCTIONS IN C

Memory classes

In the C language, four main classes of memory are distinguished: external (global), automatic (local), static, and register memory.

External (global) variables are defined outside functions and, therefore, are accessible to any of them. They can only be defined once. It was already mentioned above that the functions themselves are always global. The language does not allow to define some functions within others. The scope of the external variable extends from the point in the input file where it is declared to the end of the file. If an external variable must be referenced before it is defined or it is defined in another input file, it must be declared extern in a subroutine or file.

For example:

  extern int a;  / * Announcement a;  variable memory not  
                        reserved * / 
 

Automatic variables in relation to functions are internal or local. They begin to exist when they enter a function and are destroyed when they exit (for which the auto keyword can be used). However, it is practically not used, since in the absence of a keyword, variables by default belong to the auto class.

Static variables are declared using the static keyword. They can be internal (local) or external (global). Internal static variables, as well as automatic, are local to a single function. However, they continue to exist, and do not arise and are not destroyed each time it is called. In other words, they are their own permanent memory for a function. External static variables are available inside the remainder of the file after they are declared in it, but they are not known in other files. This, in particular, allows you to hide the data of one file from another file.

Register variables belong to the last class. The register keyword indicates that the variable in question will be used extensively. If possible, the values ​​of such variables are placed in the internal registers of the microprocessor, which can lead to a faster and shorter program (the developers of the Borland compilers claim that optimizing the compilers of this company for using register variables is done so well that instructing to use a variable as a register variable can only efficiency of the generated machine code). For register variables, you cannot take an address; they can only be automatic with valid int or char types.

Thus, there are four memory class modifiers: extern, auto, static, register. They are used in the following general form:

  memory_class_modifier type of variable_list;  
 

We have already mentioned above about initialization, i.e. on assigning different values ​​to different objects. If there is no explicit initialization, it is guaranteed that the external and static variables will have a value of zero, and automatic and register variables will have an undefined value.

  4. FUNCTIONS IN C

Function pointers

In C, a function itself cannot be the value of a variable, but you can define a pointer to a function. You can already treat it as a variable: transfer it to other functions, put it into arrays, etc.

The function code in the personal computer takes up physical memory. There is an entry point in this memory that is used to enter a function and run it. The function pointer just addresses this entry point. This will already be a regular variable and you can do everything with it that you can do with a variable.

Through the pointer you can enter the function, i.e. run it. Ad type:

  int (* f) ();  
 

says that f is a pointer to a function that returns an integer value. The first pair of brackets is necessary, without them int * f (); would mean that f is a function that returns a pointer to an integer value. After declaring a pointer to a function in the program, you can use objects: * f - the function itself; f is a pointer to a function. For any function, its name (without brackets and arguments) is a pointer to this function.

  4. FUNCTIONS IN C

Main () function arguments

You can pass some arguments to C programs. When at the beginning of the computation a call is made to main (), three parameters are passed to it. The first one determines the number of command arguments when accessing the program. The second is an array of pointers to character strings containing these arguments (one argument in one line). The third one is also an array of pointers to character strings, it is used to access the operating system parameters (environment variables).

Any such line is represented as:

  variable = value \ 0  
 

The last line can be found by the two final zeros.

Let us call the arguments of the function main (), respectively: argc, argv, and env (any other names are possible). Then the following descriptions are valid:

  main ()  
       main (int argc)  
       main (int argc, char * argv [])  
       main (int argc, char * argv [], char * env [])  
 

Suppose that on disk A: there is some prog.exe program. Refer to it as follows:

  A: \> prog.exe file1 file2 file3 <Enter>  
 

Then argv [0] is a pointer to the string A: \ prog.exe, argv [1] is to the string file1, etc. Argv [1] points to the first actual argument, and argv [3] points to the last argument. If argc = 1, then there are no parameters after the program name in the command line. In our example, argc = 4.

  4. FUNCTIONS IN C

Recursion

Recursion is a call method in which the function accesses itself.

An important point in the preparation of the recursive program is the organization of the output. Here it is easy to make the mistake that the function will consistently call itself infinitely long. Therefore, the recursive process should, step by step, simplify the problem in such a way that in the end a non-recursive solution appears for it. The use of recursion is not always desirable, as this can lead to a stack overflow.

  4. FUNCTIONS IN C

Library functions

In programming systems, subprograms for solving common problems are combined into libraries. These tasks include: calculating math functions, data input / output, processing lines, interacting with operating system tools, etc. Using library subroutines eliminates the need for developing appropriate tools and provides an additional service. Library functions are shipped with the programming system. Their declarations are given in * .h files (these are so-called include or header files). Therefore, as mentioned above, at the beginning of the program with library functions there should be lines of the form:

  #include <type_file_h__inc> 
 

For example:

  #include <conio.h> 
 

There are also tools for expanding and creating new libraries with user programs.

created: 2014-11-10
updated: 2024-11-11
191



Rating 9 of 10. count vote: 2
Are you satisfied?:



Comments


To leave a comment
If you have any suggestion, idea, thanks or comment, feel free to write. We really value feedback and are glad to hear your opinion.
To reply

Algorithmization and programming. Structural programming. C language

Terms: Algorithmization and programming. Structural programming. C language