What does “ = 0” here mean?

前端 未结 3 636
南方客
南方客 2021-01-25 14:54
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

相关标签:
3条回答
  • 2021-01-25 15:43

    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)

    0 讨论(0)
  • 2021-01-25 15:44

    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.

    0 讨论(0)
  • 2021-01-25 15:45

    See

    Default Argument

    0 讨论(0)
提交回复
热议问题