Optional arguments

This is a discussion on Optional arguments within the C++ Programming forums, part of the General Programming Boards category; Is it possible to create a function that doesn't require some of it's arguments? Like a function void dosomething(int a, ...

  1. #1
    Registered User
    Join Date
    Mar 2002
    Posts
    125

    Optional arguments

    Is it possible to create a function that doesn't require some of it's arguments? Like a function
    void dosomething(int a, int b, bool c);
    that can be called like dosomething(1,5,true); or dosomething(1,5);?
    The reason I need this is because I need a function I've already written and used to accept a slightly different input, but I don't want to track down all calls to the function to make sure they match the new defenition. Is this possible witout using an ellips (ellips='...'), like in the tutorials on this site?

  2. #2
    S­énior Member
    Join Date
    Jan 2002
    Posts
    982
    Yes, they're called default arguments -

    void dosomething(int a, int b, bool c=true);

    Due to the way in which arguments are passed to functions you always have to specify these default arguments in right to left order with no gaps so you couldn't do -

    void dosomething(int a=1, int b, bool c);

    without giving the other two arguments default values.

  3. #3
    Registered User
    Join Date
    Mar 2002
    Posts
    125
    Not even like this?
    void dosomething(int a=1, int b, bool c);
    dosomething( ,5,true);

    Anyway, that pretty much solved my problem. Thanks!

  4. #4
    geek SilentStrike's Avatar
    Join Date
    Aug 2001
    Location
    NJ
    Posts
    1,141
    dosomething( ,5,true);

    No.. you need to have the default arguments as right most arguments.
    Prove you can code in C++ or C# at TopCoder, referrer rrenaud
    Read my livejournal

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. GradeInfo
    By kirksson in forum C Programming
    Replies: 23
    Last Post: 07-16-2008, 04:27 PM
  2. command line arguments
    By vurentjie in forum C Programming
    Replies: 3
    Last Post: 06-22-2008, 07:46 AM
  3. Replies: 10
    Last Post: 09-27-2005, 01:49 PM
  4. NULL arguments in a shell program
    By gregulator in forum C Programming
    Replies: 4
    Last Post: 04-15-2004, 11:48 AM
  5. Optional Arguments
    By XSquared in forum C++ Programming
    Replies: 6
    Last Post: 09-07-2002, 06:42 PM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21