[Study notes] C06 C language programming (week 6): functions

This course comes from "The Essence of C Language Programming" in the MOOC of China University (Harbin Institute of Technology)

  This lecture will introduce some basic knowledge about functions:

1. Function call

  In programming, the use of functions is conducive to modular programming. Functions need to be defined before they can be called. The following only introduces the process of function calling.
  Every time a function call is executed, there are:

  1. Perform field protection and allocate memory for local variables (including formal parameters) in the function
  2. Copy the actual parameter value to the formal parameter, pass the value one-way (actual parameter → formal parameter)
  3. The number, type and order of actual participating formal parameters must be consistent

  When exiting from the function, there are:

  1. Return to the place of this function call according to the return address saved in the function call stack
  2. Return the function value to the calling function, while returning control to the caller
  3. Reclaim the memory allocated to all variables (including formal parameters) in the function

  For example, the function of the following function is to calculate the average value:

#include <stdio.h>
float Average(int x, int y) ;           /* compute average */

int main()
{
    
    
    int a, b ;
    scanf("%d %d",&a, &b) ;
    printf("avg = %.2f", Average(a, b)) ;
    return 0 ;
}

float Average(int x, int y)
/* compute average of x and y */
{
    
    
    float avg ;
    avg = (x + y) / 2.0 ;
    return avg ;
}
1 2
avg = 1.50

  In the main function main(), the function is used to Average()calculate the average value. In the process of control transfer main(), the statement in the function is first executed. When the function is executed Average(), the control is passed to the Average()function, and space is allocated for it, and then Average()the statement in the function is executed , And then Average()return from the function, pass control to the main function main(), and finally the function ends. In the whole process, there are function parameters , function control flow, and function return value transfer. In essence, function call is also a way to change control flow, which has certain similarities with selection and loop structure.

2. Assertions and program security

  For program design, the efficiency of the program is very important, but the correctness of the program is even more important, because the wrong program cannot get the correct result no matter how efficient it is.

2.1 Affirmation

void assert (int expression);
Evaluate assertion
If the argument expression of this macro with functional form compares equal to zero (i.e., the expression is false), a message is written to the standard error device and abort is called, terminating the program execution.

  Assertion assert()in the <assert.h>defined macro, the macro, it will detect expressiontrue and false:

  1. expressionIs true, silent and silent;
  2. expressionIf false, interrupt the program.

  It can be considered as equivalent to if(!expression) exit(1) ;an example given below:

#include <stdio.h>
#include <assert.h>
int main()
{
    
    
    int x, y ;
    scanf("%d %d",&x, &y) ;
    assert(y != 0) ;                             /* if y == 0, exit . */
    printf("%.2f\n", (float)x/y ) ;
    return 0 ;
}
1 0
Assertion failed: y != 0, file :\Documents\Desktop\myproject\Cstudy\Cprogram\main.c, line 7

  Although this can be prohibited y == 0, it assert()is only used for debugging and cannot be used as a function of the program. Therefore, the assert()following situations are recommended :

  1. Check the correctness of various assumptions in the program
  2. To prove or test that an impossible situation does not happen

  Such as the following situation:

int MakeNumber(void)
{
    
    
	int number;
	number = rand() % 100 + 1;
	assert(number >= 1 && number <= 100);
	return number;
}

  It is worth noting that it works assert()in the debugging phase of the function:

  1. Debug version is
    used for internal debugging- assertonly works in Debug version
  2. Release version is
    released for users to use-the compiler will skip and assertnot generate check code

2.2 Security of the program

  Program security is a big topic. Here, we consider the following example to introduce it: To
  exchange two values, there are two methods below:

/* method 1 */
t = a ;
a = b ;
b = t ;
/* method 2 */
a = a + b ;
b = a – b ;
a = a – b ; 

  The known conclusion is method 1superior method 2, so what method 2is the problem? Welcome to discuss in the comment section!

3. Programming Quiz

1. Three-digit factorial sum

The content of the title
  assumes that there is such a three-digit m, whose hundreds, tens, and ones digits are respectively a, b, c. If m = a!+b!+c!, then this three digit is called a three-digit factorial sum (convention 0!=1). Please program to calculate and output all three-digit factorial sums.
 Function prototype: long Fact(int n);
 Function function: Calculate the factorial of n

#include <stdio.h>
long Fact(int n) ;
int main()
{
    
    
    int m, a, b, c ;
    for(m=100; m<1000; m++)
    {
    
    
        a = m / 100 ;               /* the hundreds place of m */
        b = (m / 10) % 10 ;         /* the tens place of m */
        c = m % 10 ;                /* the ones place of m */
        if(m == (Fact(a)+Fact(b)+Fact(c)))
        {
    
    
            printf("%d\n", m) ;
        }
    }
    return 0 ;
}
long Fact(int n)
/* compute factorial of n */
{
    
    
    long sum = 1 ;
    int i ;
    for(i = n; i >= 1; i--)
    {
    
    
        sum *= i ;
    }
    return sum ;
}
145

4. Past review

1. [Study notes] C language programming (1st week): Variables and constants
2. [Study notes] C language programming (2nd week): C operators and expressions
3. [Study notes] C language programs Design (the third week): input and output
4. [study notes] C language programming (fourth week): select structure
5. [study notes] C language programming (fifth week): loop structure
6. [study Notes] C language programming (supplement in week 5): exercises with loop structure

Guess you like

Origin blog.csdn.net/Stu_YangPeng/article/details/114211105