Today, I lost my fortune. I sent an email about function definition to the project team email list, discussing the function definition in the following form:
#include<stdio.h>void function(arg1, arg2)int arg1;int arg2;{ printf("arg1=%d, arg2=%d", arg1, arg2);}int main(){ function(); function(1); function(1,2); return 0;}
The above code output is:
arg1=134513424, arg2=134513755arg1=1, arg2=134513755arg1=1, arg2=2
At first, I was surprised that functions in C could be defined in this way, and different numbers of parameters can be input when this function is called.
Later, in the mail list, the three predecessors raised doubts. This kind of function definition is a very old definition method called K & R style definition, currently, all the C function definitions we use are ANSI style.
If the above Code comments the following code
// function(); // function(1); // function(1,2);
When the following code is called
function(1,2); function(1); function();
Output:
arg1=1, arg2=2arg1=1, arg2=2arg1=1, arg2=2
You must be as surprised as I am. This function has the function of memorizing parameters. Actually, it is not. The calls of these three statements of code are sequential. That is to say, they use the same stack, the value in the stack has not changed. If a function call with parameters is added to the Code of the three statements, the output results will be different.
For the function defined above, when calling, the number of input parameters can be at most 2. If more than 3 parameters are input, an error is returned, what if I want to input three, four, and five parameters? The following code is available.
1 #include<stdio.h> 2 3 void function(); 4 5 int main(){ 6 7 function(1,2); 8 function(1,2,3); 9 function(1,2,3,4);10 11 return 0;12 }13 14 void function(int arg1, int arg2)15 {16 printf("arg1=%d, arg2=%d", arg1, arg2);17 }
Advanced!
PS: the above Code test environment is centos and GCC 4.4.5
In addition, you can generate an assembly code by using gcc-s sourcefile. Note that it is uppercase S.