The C language does not have the concept of parameter default values. You can use macros to simulate parameter default values:
(For a function with multiple parameters, you need to write each parameter in the parameter list during calling, but you can put the default parameter before the non-default parameter)
The following code cannot be passed in c:
Define fun ():
Int fun (int a, int B = 10) ... ...
{ .... ... ... ....
Return a + B;
} .. ..
Main function code: .... ....
Int main () ......
{
Printf (% d, fun (10 ));
Return 0;
}
........................................ ......................
An error occurs when fun (10) is called during compilation. Note that this code is correct in C ++.
........................................ ......................
Code after macro improvement:
# Include
# Define funi (a) fun (a, 10)
Int fun (int a, int B)
{
Return a + B;
}
Int main ()
{
Int a = 10;
Printf (% d% D, fun (a, 10), funi ());
Return 0;
}
Result: 20
[Cpp]View plaincopy
- # Include
-
- # Define DEFARG (name, defval) (# name [0])? (Name + 0): defval)
-
- Int _ f1 (int I)
- {
- Return 2 * I;
- }
- # Define f1 (arg0) _ f1 (DEFARG (arg0, 0 ))
-
- Int _ f2 (int I, int j)
- {
- Return I + j;
- }
- # Define f2 (arg0, arg1) _ f2 (DEFARG (arg0, 0), DEFARG (arg1, 1 ))
-
- Int main ()
- {
- Printf (% d, f1 ());
- Printf (% d, f1 (1 ));
-
- Printf (% d, f2 (,));
- Printf (% d, f2 (2 ,));
- Printf (% d, f2 (, 3 ));
- Printf (% d, f2 (4, 5 ));
- Return 0;
- }
# Include
# Define DEFAULT 40/* DEFAULT parameter value */# define FUN (A) fun (# ##-) /* macro used to implement default parameters */int f (int n)/* function used to experiment with default parameters */{return printf (% d, n );} int fun (const char * a)/* determines the function called by the function. The return value type must be the same as that of the f () function to be called */{int n; /* the type of the variable must be the same as that of the f () function parameter */if (a [0] = '-') n = DEFAULT; else sscanf (, % d, & n); return f (n);} int main (void) {FUN (); FUN (67); return 0 ;}
Ps: if there is a header file:GetStr. h# Define getStr () _ getStr (TestFun.txt); // set default filename in. c
Void _ getStr (char filename []);
GetStr. cVoid _ getStr (char filename []) {
...}Main. c# Include getStr. h void main () {getStr ();}
Ref:
Http://blog.csdn.net/broook/article/details/7208408 http://nonoob.is-programmer.com/posts/36769.html http://www.myexception.cn/c/232391.html
Http://wenku.baidu.com/view/1ffed5d86f1aff00bed51eea.html http://blog.csdn.net/broook/article/details/7208408
From http://blog.csdn.net/pipisorry/article/details/25437893