The basic learning course of function in C language programming _c language

Source: Internet
Author: User
Tags function definition function prototype

The functions in C language are equivalent to subroutines or functions in Fortran language, and are equivalent to processes or functions in Pascal language. Functions provide an easy way to compute the encapsulation, and you do not need to consider how it is implemented after you use the function. With a properly designed function, programmers do not have to think about how functionality is implemented, but simply know what functionality it has. Functions can be used in C language in a simple, convenient and efficient way. We often see short functions that are called only once after a definition, which makes the code snippet more readable and easy to read.

So far, the functions we use (such as printf, GetChar, and Putchar) are functions provided in the function library. Now, let's write some functions ourselves. The C language does not provide a exponentiation-like power operator like a Fortran language, and we now describe the method of function definition by writing a exponentiation function power (m, N). The Power (m, n) function computes the N-exponentiation of an integer m, where n is a positive integer. For function call Power (2,5), the result value is 32. This function is not a practical exponentiation function, it can only handle the positive integer power of a smaller integer, but this is sufficient to illustrate the problem. (A function pow (x, y) that calculates XY is provided in the standard library.) )

Here is the definition of function power (m, N) and the main program that invokes it, so that we can see a complete program structure.

#include <stdio.h>
int power (int m, int n);

/* Test Power function *
/main ()
{
 int i;
 for (i = 0; i < ++i)
 printf ("%d%d%d\n", I, Power (2,i), Power ( -3,i));
 return 0;
}

/* Power:raise base to n-th power; N >= 0 *
/int power (int base, int n)
{
 int i, p;
 p = 1;
 for (i = 1; I <= n; ++i)
 p = p * Base;
 return p;
}

The general form of a function definition is:

Returns the value type function name (0 or more argument declarations)
{
 declares a partial
 statement sequence
}

Function definitions can appear in any order in one source file or multiple source files, but the same function cannot be split into multiple files. If the source program is scattered across multiple files, more work needs to be done when compiling and loading, but this is the reason for the operating system, not the attribute of the language. Let's assume that both the main and the power functions are in the same file, so that the knowledge you have learned about running the C language program is still valid.

The main function called two power functions in the following statements: printf ("%d%d%d\n", I, power (2, I), power (-I, 3)); At each call, the main function passes two arguments to the power function, and when the call execution completes, the power function returns a formatted integer to the main function and prints it. In an expression, power (2, I) is an integer equal to 2 and I

The first line of the power function, int power (int base, int n), declares the type of the parameter, the name, and the type of the result that the function returns. The parameters used by the power function are only valid inside the power function and are not visible to any other function: Other functions can use the same parameter name without causing a conflict. The variables I and P are also like this: I in the power function has nothing to do with I in the main function.

We usually refer to the variables appearing in parentheses in the function definition as formal parameters, while the values corresponding to formal parameters in function calls are called actual parameters.

The result of the power function calculation is returned to the main function through the return statement. Keyword return can be followed by any expression, in the form of a return expression;

A function does not necessarily have a return value. A return statement without an expression returns control to the caller, but does not return a useful value. This equates to the "end of the function" when the right end curly brace is reached. The keynote function can also ignore the value returned by the function.

The reader may have noticed that there is a return statement at the end of the main function. Because main itself is also a function, you can also return a value to its caller, which is actually the execution environment for the program. Generally, a return value of 0 indicates a normal termination, and a return value of not 0 indicates an exception or an error termination condition. For brevity, the previous main function omits the return statement, but we'll include the returns statement in a later main function to remind you that the program is also going to run the environment back to its state.

statement int power (int m, int n) that appears before the main function; Indicates that the power function has two parameters of type int and returns a value of type int. This declaration, called a function prototype, must be consistent with the definition and usage of the power function. If the definition, usage of the function is inconsistent with the function prototype, an error occurs.

The function prototype does not require the same as the parameter name in the function declaration. In fact, the name of the parameter in the function prototype is optional, so that the function prototype above can also be written in the following form: int power (int, int);

However, the appropriate parameter names can be very descriptive, so we always specify the parameter names in the function prototype.

In retrospect, the biggest difference between ANSI C and an earlier version of C is the difference between the declaration of a function and the way it is defined. As originally defined in the C language, the power function should be written in the following form:

/* Power:raise base to n-th power; N >= 0 *
/* (Old-style Version)
/power (base, n)
int base, n;
{
 int i, p;
 p = 1;
 for (i = 1; I <= n; ++i)
 p = p * Base;
 return p;
}

Where the parameter name is specified in parentheses, and the argument type is declared before the left curly brace. If no type is declared for a parameter, the type int is the default. The function body is the same as the ANSI C form.

In the original definition of C, the power function can be declared at the beginning of the program in the following form: int power ();

Parameter lists are not allowed in function declarations so that the compiler cannot check the legality of power function calls at this time. In fact, the power function is assumed to return a value of type int by default, so the entire function declaration can be omitted altogether.

In the function prototype syntax defined in ANSI C, the compiler can easily detect errors in the number and type of arguments in a function call. ANSI C still supports legacy function declarations and definitions, so there can be at least one transition phase. However, we strongly recommend that the reader should use the new style of the compiler to declare the method of function prototype.

The following is given on MFC implementation:

void Cnowamagic_mfcdlg::onbnclickedok ()
{
 //TODO: Add control Notification Handler code
 //cdialogex::onok () here;
 Get edit 
 cedit* base;
 cedit* N;
 Base = (cedit*) GetDlgItem (idc_edit1);
 n = (cedit*) GetDlgItem (idc_edit2);

 CString str1;
 CString str2;
 CString Showstr;

 Char tmp[10] = "";
 Base-> GetWindowText (STR1);
 N-> GetWindowText (str2);

 char* pstr = (LPTSTR) LPCTSTR (str1); 
 int my_base = _ttoi (str1); 
 int my_n = _ttoi (str2);

 int result = Power (my_base, my_n);
 
 Showstr = itoa (result,tmp,10);

 CString str = _t ("The result of the exponentiation operation is:");

 MessageBox (str + showstr,_t ("program run Result"), MB_OK);
 Str. ReleaseBuffer ();
}

int power (int base, int n)
{
 int i, p;
 p = 1;
 for (i = 1; I <= n; ++i)
 p = p * Base;
 return p;
}

Program Run Result:

CString int can be used

 int my_base = _ttoi (STR1);

Function declarations Note that you want to write the header function.

Pass value Call and parameter
programmers who are accustomed to other languages (especially Fortran) may be unfamiliar with the way the function parameters of C are passed. In the C language, all function arguments are passed by value. That is, the parameter values passed to the called function are stored in a temporary variable rather than in the original variable. This is different from some other languages, for example, Fortran is called by reference, and Pascal uses the Var argument, in which the called function must access the original argument instead of accessing the local copy of the parameter.

The main difference is that in C, a called function cannot directly modify the value of a variable in the calling function, but only the value of its private temporary copy.

The benefits of a value call outweigh the disadvantages. In a called function, a parameter can be thought of as a local variable that is easy to initialize, so there are fewer additional variables to use. This program can be more compact and concise. Side, the following power function uses this property:

/* Power:raise base to n-th power; n >= 0; Version 2 *
/int power (int base, int n)
{
 int p;
 for (p = 1; n > 0;--n)
 p = p * Base;
 return p;
}

Where the parameter n is used as a temporary variable and is decremented by the subsequent for Loop statement until its value is 0, so that no additional introduction of the variable i;power any operation of n within the function does not affect the original parameter value of n in the calling function.

If necessary, you can also allow the function to modify variables in the keynote function. In this case, the caller needs to provide the address of the variable whose value is to be set to the called function (the address is technically the pointer to the variable), and the called function needs to declare the corresponding parameter as a pointer type and indirectly access the variable through it.

If it is an array parameter, the situation is different. When an array name is used as an argument, the value passed to the function is the position or address of the starting element of the array-it does not copy the array element itself. In the called function, you can access or modify the value of the array's meta cable by using an array subscript.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.