Default Arguments

I am doing something wrong here and I'm not sure what.

This is my code and the output should be 2 but the actual output is 1.

1
2
3
4
5
6
7
#include <iostream>

int main(int a = 2)
{
    std::cout << a << "\n";
    return 0;
}


This is the only warning from the build log

warning: 'int main(int)' takes only zero or two arguments [-Wmain]
Last edited on
Ummm.... Main is a standardized function, you can't modify it. Maybe you want this:
1
2
3
4
5
6
int func(int a = 2) { return a; }

int main() {
    std::cout << func(5) "\t" << func() << "\n";
    return 0;
}
Last edited on
Ahh, thank you.

I'm trying to learn about default arguments. I didn't realize that the main function had a restriction like that.

WINMAIN doesn't seem to have that restriction but I haven't tried to mix that with c++ yet. Maybe some day soon!

Although, it does appear you can still initialize variables in the main function, just not give them values.

Like this setup int main( int argc, char** argv )
Last edited on
You cannot use default arguments on main. They can only be used on other functions. Look at the following example.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include <iostream>
using namespace std;

void showNumber( int n = 5 )
{
    cout << n << endl;
}

int main( )
{
    showNumber( 594 );
    showNumber( );
    return 0;
}


Will give the following output.

594
5


*EDIT* I posted my reply after you marked it as solved.
int main( int argc, char** argv ) is command line arguments. argc is number of arguments, argv is a 2D char array.
Lets say my program is called MyGame, in the command line I could type this.
MyGame -s newGame, argv would be this argv[1] = "-s", argv[2] = "newGame"
Last edited on
That does seem like a useful thing to be able to do vasilenko.

edit..

So you can only have a default argument in the main function if it's input from the command line?
Last edited on
main() is not a normal function. You don't get to decide what arguments it takes. You must specify it one of the prescribed ways:

int main( int argc, char** argv )

int main()

Or a compiler-specific way.

Hope this helps.
Last edited on
This is a good explanation about them.
http://www.cplusplus.com/articles/DEN36Up4/
Topic archived. No new replies allowed.