Optional argument

This is a discussion on Optional argument within the C++ Programming forums, part of the General Programming Boards category; Is possible to make a function with 3 arguments, but one of them being optional? like this: Code: string stringsum(string ...

  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,796
    >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,262
    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 12:23 PM.

  4. #4
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    22,308
    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.
    C + C++ Compiler: MinGW port of GCC
    Version Control System: Bazaar

    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, 06:30 AM
  2. member as default argument
    By MarkZWEERS in forum C++ Programming
    Replies: 2
    Last Post: 03-23-2009, 09:09 AM
  3. Peculiar malloc / command argument question
    By Beowolf in forum C Programming
    Replies: 4
    Last Post: 09-11-2007, 12:54 AM
  4. Screwy Linker Error - VC2005
    By Tonto in forum C++ Programming
    Replies: 5
    Last Post: 06-19-2007, 03:39 PM
  5. Nested loop frustration
    By caroundw5h in forum C Programming
    Replies: 14
    Last Post: 03-15-2004, 09:45 PM

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