What does " = 0" here mean?
int foo (int a , int b = 0)
I just read this code. I don't understand what " = 0" means?
I would also like to know why int foo (int a = 0, int b)
d开发者_开发百科oes not compile.
b is a parameter with a default value of 0. So the function can be called (e.g.):
foo(3, 4)
with a and b equal to 3 and 4
or:
foo(5)
with a and b equal to 5 and 0.
int foo (int a=0, int b)
is wrong because default parameters can only appear at the end. Imagine you had:
int foo (int a = 0, int b, int c = 1)
and called it like:
foo(3, 4)
The compiler wouldn't know which you were omitting. To avoid such situations, you can't put a default parameter before a non-default one.
See
Default Argument
It sets the default value for the parameter "b" to the function foo, so that the call foo(345)
is equivalent to the call foo(345, 0)
精彩评论