A parameter declared inside main is not same as parameter declared in another function.. Why?

I notice a variation in this two results:

1
2
3
4
5
6
7
8
9
10
int sub(int x=2, int y=1)
{int z;
z=x-y;
return z;}

int main (int a=2, int b=1)
{int result;
result=a-b;
cout<<result<<"\n";
cout<<sub()<<"\n";

result=-3477279
z=1

why is this happening when a=x=2 and b=y=1?
Your main function should not take any arguments (except for optional command line args).

Here is the warning I get when I compile that code
[Warning] second argument of 'int main(int, int)' should be 'char **'


What's happening is that "b" is uninitialized, so result will be undefined too. "a" happens to be defined because of how argc is an int in int main(int argc, char* argv[])
Last edited on
fix code:
1
2
3
4
5
6
7
8
9
10
11
12
13
int sub(int x=2, int y=1)
{int z;
z=x-y;
return z;}

int main ()
{
    int a=2; int b=1;
    int result;
    result=a-b;
    cout<<result<<"\n";
    cout<<sub();
}

i dont know the expanation
Lol justin.. Yes, i did that too but what rule in c++ says main cannot use
 
 int main (int a=2, int b=1) 

when the function
int sub(int a=2, int b=1)
holds correct.

My compiler dev c++ is outdated no doubt but there has to be an explanation to this weird result.

This is possible too
1
2
3
4
5
int main (int a, int b)
{int result;
a=2; b=1;
result=a-b;
cout<<result;}


result=1
what is wrong wit int a=2 when int a is correct.?
Last edited on
thats why i said i dont know the explanation
maybe the main function param is too sensitive haha
Last edited on
The compiler thinks that you're defining your main function as int main(int argc, char* argv[]). The first argument is okay because argc is an int will always be at least 1, second argument is undefined (at first) because you're trying to define it as an int when it wants a char**.
Last edited on
what rule in c++ says main cannot use

1. See: http://www.cplusplus.com/forum/beginner/26251/#msg140009

2. A question for you: Who/what does use the default values for function parameters?
Last edited on
Thankz ganado.. That helped alot. I thot main can do the same function as the other called function. I was unaware of main(int argc, char* argv[]) though i dint understand it fully i got the reason why i got the weird answer.. I wil not try that again.. :-D
Keskiverto.. Ur reference helped me undrstand ganado's comment.. Thanx all. I'll leave a link for who might need help with this argc and argv http://stackoverflow.com/questions/3024197/what-does-int-argc-char-argv-mean
Last edited on
Topic archived. No new replies allowed.