Function-declaration, definition, and call
1. If the function is not declared, define it before calling:
#include <stdio.h>
/* Define a big value function */
Int MAX (int x, int y ){
If (x> y)
Return x;
Else
Return y;
}
/* Define a small value function */
Int MIN (int x, int y ){
Return x <y? X: y;
}
int main(void)
{
int a = 5;
int b = 6;
/* Call a function */
Printf ("% dn", MAX (a, B ));
Printf ("% dn", MIN (a, B ));
Getchar ();
Return 0;
}
2. You can declare in the function header:
#include <stdio.h>
int main(void)
{
int a = 5;
int b = 6;
/* Declare the function to be used in the function header */
Int MAX (int x, int y );
Int MIN (int x, int y );
/* Call a function */
Printf ("% dn", MAX (a, B ));
Printf ("% dn", MIN (a, B ));
Getchar ();
Return 0;
}
/* Define a big value function */
Int MAX (int x, int y ){
If (x> y)
Return x;
Else
Return y;
}
/* Define a small value function */
Int MIN (int x, int y ){
Return x <y? X: y;
}
3. But should be declared in the file header:
The Declaration of the function prototype is declared in the header file (*. h) in actual use.
#include <stdio.h>
/* Declare the function to be used in the file header */
Int MAX (int x, int y );
Int MIN (int x, int y );
Int main (void)
{
Int a = 5;
Int B = 6;
/* Call a function */
Printf ("% dn", MAX (a, B ));
Printf ("% dn", MIN (a, B ));
Getchar ();
Return 0;
}
/* Define a big value function */
Int MAX (int x, int y ){
If (x> y)
Return x;
Else
Return y;
}
/* Define a small value function */
Int MIN (int x, int y ){
Return x <y? X: y;
}
4. functions can be called, but cannot be nested:
#include <stdio.h>
void PrintSum(int x, int y);
int sum(int x, int y);
int main(void)
{
PrintSum(1,2);
PrintSum(111,222);
getchar();
return 0;
}
void PrintSum(int x, int y) {
printf("%d + %d = %d;", x, y, sum(x,y));
putchar('n');
}
int sum(int x, int y) {
return x + y;
}
5. functions without parameters or returned values:
If the function does not have a parameter, it is best to use fun (void), but also fun;
If the function does not return a value, specify the return type as void;
Brackets are also required to call a function without parameters in c/c ++.
#include <stdio.h>
void prn(void);
Int main (void)
{
Prn ();/* call a function without parameters */
Getchar ();
Return 0;
}
void prn(void) {
printf("okn");
}
6. When declaring a function, you can omit the form parameter:
#include <stdio.h>
Int sum (int, int, int);/* omitted form parameter */
int main(void)
{
printf("%dn", sum(1,2,3));
getchar();
return 0;
}
int sum(int x, int y, int z)
{
return(x + y + z);
}
7. Generally, the number of function parameters should not exceed 7:
However, C 99 supports up to 127 parameters.
#include <stdio.h>
int sum(int, int, int, int, int, int, int);
int main(void)
{
printf("%dn", sum(1,2,3,4,5,6,7));
getchar();
return 0;
}
int sum(int a, int b, int c, int d, int e, int f, int g)
{
return(a + b + c + d + e + f + g);
}