Why this recursive function works?

Dec 28, 2018 at 1:37pm
This should return true if a number belongs to an array of numbers and false if not.

I don't know how this works, because I call the function only by check(nr,n,v).But in the function I declared a variable "i", without giving it a value in the main.Why does it not give an error, as i call the function check(nr,n,v), not (nr,nr,v,i)?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
#include<iostream>

using namespace std;

int check(int nr, int n, int v[],int i=0)
{
    if(v[i]==nr)
        return true;
    if(i==n)
        return false;

    check(nr,n,v,i+1);
}


int main()
{   int nr,n=4;
    int v[n];
    cin>>nr;
    for(int i=0;i<n;i++)
        v[i]=i;

    if(check(nr,n,v))
        cout<<"it belongs";
    else
        cout<<"it does not belong";

}
Dec 28, 2018 at 1:41pm
int check(int nr, int n, int v[],int i=0)

See the int i=0? That means "if the function is called without providing a value for i, set i to zero and carry on".

We call this a default argument.
Dec 28, 2018 at 1:42pm
Thank you
Dec 28, 2018 at 2:02pm
About default arguments,

why is
int check(int a, int b=0);
legal, whereas
int check(int a=0, int b)
illegal?

What I'm saying is, why is it illegal to have function arguments without default values follow arguments which do have default values?

I visualize int check(int a, int b);
as :

1
2
3
4
5
6
{ // check's block
int a;
int b;
a = actual_parameter
b = actual_parameter
}


Is that wrong?

If it's right then why would int check(int a=0, int i); be wrong?
it would be

1
2
3
4
5
6
{ // check's block
int a = 0;
int b;

a = actual_parameter;
b = actual_parameter;


So then if that were the case then int check(int a=0, int i); should be legal.. So how is the compiler actually interpreting the function and WHY can't uninitialized arguments follow default arguments?
Last edited on Dec 28, 2018 at 2:03pm
Dec 28, 2018 at 2:41pm
You also need to propagate the return result through all the recursive calls.
Like so.
1
2
3
4
5
6
7
8
9
int check(int nr, int n, int v[],int i=0)
{
    if(v[i]==nr)
        return true;
    if(i==n)
        return false;

    return check(nr,n,v,i+1);  //!! must return result
}
Dec 28, 2018 at 5:31pm
why is
int check(int a, int b=0);
legal, whereas
int check(int a=0, int b)
illegal?

Default arguments must be the last arguments of the function. To see why, consider this hypothetical example:
int check(int a=0, int b, int c=1);
...
int x = check(1,2); // Is that check(1,2,1) (c get default) or check(0,1,2) (a gets default)?
Dec 29, 2018 at 2:42am
Oh okay so in short having defaulted arguments before non defaulted arguments would make the default obsolete because the defaulted argument would have to be overwrittenbin order to give a value for non default.. So its not a compiler issue its just standard.
Topic archived. No new replies allowed.