Custom functions for the C language basics tutorial

  • 2020-05-30 20:51:00
  • OfStack

Write the program first:


#include <stdio.h>

int add(int x, int y)
{
  int z = x + y;
  return z;
}

int main()
{
  int a = 1;
  int b = 2;
  int c = add(a, b);
  printf("c = %d\n", c);
  
  return 0;
}

Operation results:


c = 3


Program analysis:
(1)
The form of function definition is:
Type function name (type form parameter...)
{
The body of the function
}

(2)
Corresponding to our program, we define a function named add, and the return value type of the function represented by int to the left of add. Corresponds to the type of z returned in the body of the function.

(3)
x and y are formal parameters, and a and b in main() function add(a,b) are actual parameters.

(4)
add(a,b) in the main function is not followed by a curly brace, indicating that it is a function call, not a function definition. The specific add function is defined above the main function.

(5)
When the add function is called, the actual parameters (arguments) are passed to the formal parameters (formal parameters), such that x = a = 1 and y = b = 2

(6)


z = x + y = 1 + 2 = 3

(7)
int c = add(a, b) indicates that the add function is assigned to c. So c = add(1, 2) = z = 3. So c is equal to 3


Related articles: