Thread: Optional argument

  1. #1
    Registered User
    Join Date
    Dec 2005
    Posts
    17

    Optional argument

    Is possible to make a function with 3 arguments, but one of them being optional? like this:

    Code:
    string stringsum(string s1, strings2, strings3){
    return (s1+s2+s3);
    }

    so if i use stringsum("I , "love ", "you.") it will work
    and if i use ("I ", love.") it'll work too

  2. #2
    Code Goddess Prelude's Avatar
    Join Date
    Sep 2001
    Posts
    9,897
    >Is possible to make a function with 3 arguments, but one of them being optional?
    Yes, as long as it's the last one:
    Code:
    string stringsum(string s1, strings2, strings3 = "you")
    {
      return (s1+s2+s3);
    }
    My best code is written with the delete key.

  3. #3
    The superhaterodyne twomers's Avatar
    Join Date
    Dec 2005
    Location
    Ireland
    Posts
    2,273
    string stringsum(string s1, strings2="", strings3="")
    {
    return (s1+s2+s3);
    }
    will default the last two to blanks. However, you must start at the VERY right hand side, and work over with this. Just put whatever you want inside the ""'s, so you could default whichever to whatever.
    Last edited by twomers; 09-23-2006 at 11:23 AM.

  4. #4
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,413
    Yes.
    Code:
    string stringsum(string s1, string s2, string s3 = "you.") {
        return s1 + s2 + s3;
    }
    EDIT:
    See? Spend a little time to make the latter two arguments actually have a return type, and I end up getting beaten to it by two people.
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Pointer to List Iterator As Function Argument
    By bengreenwood in forum C++ Programming
    Replies: 8
    Last Post: 06-17-2009, 05:30 AM
  2. member as default argument
    By MarkZWEERS in forum C++ Programming
    Replies: 2
    Last Post: 03-23-2009, 08:09 AM
  3. Peculiar malloc / command argument question
    By Beowolf in forum C Programming
    Replies: 4
    Last Post: 09-10-2007, 11:54 PM
  4. Screwy Linker Error - VC2005
    By Tonto in forum C++ Programming
    Replies: 5
    Last Post: 06-19-2007, 02:39 PM
  5. Nested loop frustration
    By caroundw5h in forum C Programming
    Replies: 14
    Last Post: 03-15-2004, 09:45 PM