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)?
#include<iostream>
usingnamespace std;
int check(int nr, int n, int v[],int i=0)
{
if(v[i]==nr)
returntrue;
if(i==n)
returnfalse;
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";
}
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?
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)?
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.