Thread: Function that returns string

  1. #1
    Registered User
    Join Date
    Apr 2008
    Posts
    14

    Function that returns string

    I would like to have something like this in my blackjack program :

    Code:
    string suit(int cardvalue) {
    
        if (cardvalue<13)
            return "Spades";
        else if (cardvalue < 26)
           return "Diamonds";
    }
    And so on and so forth.

    But right now, all I can do is have it return 'S' (Spades), 'D'
    (Diamonds), etc etc (The one letter being a character, as it will let
    the function return a character).

    Any help is appreciated.

  2. #2
    and the Hat of Guessing tabstop's Avatar
    Join Date
    Nov 2007
    Posts
    14,336
    If we're in C (checks board...), then there is no such thing as string. There is such a thing as const char *, though, which is what "Spades" and "Diamonds" are.

  3. #3
    Registered User
    Join Date
    Apr 2007
    Location
    Sydney, Australia
    Posts
    217
    That is c++. In C you woudnt return a string, instead you pass a pointer to a "char array" that the text will be copied to.

    Code:
    void suit(int cardValue, char* out, size_t outLen)
    {
        if (cardValue < 13)
            strncpy(out, "Spades", outLen);
        else if (cardvalue < 26)
            strncpy(out, "Diamonds", outLen);
        else *out = 0; //Null terminate
    }
    
    int main(int argc, char* argv[])
    {
        char textBuffer[1024];
        suit(4, textBuffer, sizeof(textBuffer));
        printf("&#37;s\n", textBuffer);    //Should print "Spades"
        return 0;
    }

  4. #4
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,661
    Well it depends on how you defined 'string' in your C program.
    Or how you're trying to print it for that matter.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

  5. #5
    Officially An Architect brewbuck's Avatar
    Join Date
    Mar 2007
    Location
    Portland, OR
    Posts
    7,396
    Quote Originally Posted by 39ster View Post
    That is c++. In C you woudnt return a string, instead you pass a pointer to a "char array" that the text will be copied to.
    Or, of course, allocate a buffer, put the string there, and return a pointer to the buffer. The caller is responsible for freeing it. This is often the only option if the calling code has no way of telling a priori how big a buffer will be necessary.

  6. #6
    Registered User
    Join Date
    Apr 2008
    Posts
    14
    Never mind, I got it:

    Code:
    char *get_suit (int val)
    {
       int suit;
       static char *suits[] = {"spades", "diamonds", "clubs", "hearts", "wtf"};
    
       if (val < 13) {
           suit = 0;
       } else if (val < 26) {
          suit = 1;
       } else if (val < 39) {
          suit = 2;
       } else if (val < 53) {
          suit = 3;
       } else {
          suit = 4;  // should never happen
       }
    
       return suits[suit];

  7. #7
    Hurry Slowly vart's Avatar
    Join Date
    Oct 2006
    Location
    Rishon LeZion, Israel
    Posts
    6,788
    the function should return const char *
    All problems in computer science can be solved by another level of indirection,
    except for the problem of too many layers of indirection.
    – David J. Wheeler

  8. #8
    Kernel hacker
    Join Date
    Jul 2007
    Location
    Farncombe, Surrey, England
    Posts
    15,677
    Quote Originally Posted by vart View Post
    the function should return const char *
    and it should be
    Code:
    const static char suits[]...
    -
    Mats
    Compilers can produce warnings - make the compiler programmers happy: Use them!
    Please don't PM me for help - and no, I don't do help over instant messengers.

  9. #9
    Hurry Slowly vart's Avatar
    Join Date
    Oct 2006
    Location
    Rishon LeZion, Israel
    Posts
    6,788
    you mean
    Code:
    const static char* suits[]...
    All problems in computer science can be solved by another level of indirection,
    except for the problem of too many layers of indirection.
    – David J. Wheeler

  10. #10
    Registered User
    Join Date
    Oct 2001
    Posts
    2,129
    Quote Originally Posted by tabstop View Post
    If we're in C (checks board...), then there is no such thing as string. There is such a thing as const char *, though, which is what "Spades" and "Diamonds" are.
    technically, they are char[7] and char[9].

  11. #11
    Registered User Agent Smith's Avatar
    Join Date
    Apr 2008
    Posts
    2
    Code:
    char *get_suit(int val)
    {
      static char *suit[] = {"spades","diamonds","clubs","hearts"};
      return suit[val / 13];
    }

  12. #12
    Hurry Slowly vart's Avatar
    Join Date
    Oct 2006
    Location
    Rishon LeZion, Israel
    Posts
    6,788
    this version has same const correctness problems, and also adds problems with out of bounds access on the incorrect input. So how it is better?
    All problems in computer science can be solved by another level of indirection,
    except for the problem of too many layers of indirection.
    – David J. Wheeler

  13. #13
    Registered User Agent Smith's Avatar
    Join Date
    Apr 2008
    Posts
    2
    It's better because will execute faster than a sequence of if-then expressions.
    The compiler will also generate less object code.

    I don't believe in adding range checking to each and every function - if you're passing in out-of-range values, your calling code is buggy!

    const qualifier? Only for variables.
    And most compilers don't enforce it anyway. Of documentation value only (perhaps).

  14. #14
    C++まいる!Cをこわせ!
    Join Date
    Oct 2007
    Location
    Inside my computer
    Posts
    24,654
    Quote Originally Posted by Agent Smith View Post
    It's better because will execute faster than a sequence of if-then expressions.
    The compiler will also generate less object code.
    But it's worse than the previous code because
    a) It's lacking const.
    b) It's easy to do out-of-bounds.

    I don't believe in adding range checking to each and every function - if you're passing in out-of-range values, your calling code is buggy!
    Then add an assert to check for a programming error!

    const qualifier? Only for variables.
    And most compilers don't enforce it anyway. Of documentation value only (perhaps).
    This isn't true in the slightest. A const variable cannot be modified (without hacks). The compiler must ensure this. There it should be const char (see http://cpwiki.sourceforge.net/Common...be_const_char).

    Better code:
    Code:
    /* Now caller cannot modify returned string */
    const char* get_suit(uint32_t val)
    {
        static const char* suit[] = {"spades","diamonds","clubs","hearts"};
        assert(val <= 52); /* Make sure no out of bounds access */
        return suit[val / 13];
    }
    Last edited by Elysia; 04-26-2008 at 07:55 AM.
    Quote Originally Posted by Adak View Post
    io.h certainly IS included in some modern compilers. It is no longer part of the standard for C, but it is nevertheless, included in the very latest Pelles C versions.
    Quote Originally Posted by Salem View Post
    You mean it's included as a crutch to help ancient programmers limp along without them having to relearn too much.

    Outside of your DOS world, your header file is meaningless.

  15. #15
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,661
    > It's better because will execute faster than a sequence of if-then expressions.
    An average of two comparions is always going to be a lot quicker than a division. Comparisons typically take a single tick, but divisions take tens of clock ticks at the best of time.

    The number of characters you use in the source code is no real indication of how fast the resultant code will take to run.

    > if you're passing in out-of-range values, your calling code is buggy!
    I'm sure that thought will be very comforting when you're staring at a random consequence of that and the deadline for shipping is looming.
    Using copious asserts allows you to pinpoint problems at the earliest possible moment, in their most accurate description. Not days or months later in some obscure side effect of the original error.

    > And most compilers don't enforce it anyway.
    Well from your now deleted post, it seems you're using some ancient fossil, so I can see why you would draw that conclusion.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 11
    Last Post: 05-19-2009, 08:17 AM
  2. Question..
    By pode in forum Windows Programming
    Replies: 12
    Last Post: 12-19-2004, 07:05 PM
  3. Contest Results - May 27, 2002
    By ygfperson in forum A Brief History of Cprogramming.com
    Replies: 18
    Last Post: 06-18-2002, 01:27 PM
  4. Custom String Parsing Function
    By Unregistered in forum C++ Programming
    Replies: 2
    Last Post: 05-01-2002, 11:07 PM
  5. qt help
    By Unregistered in forum Linux Programming
    Replies: 1
    Last Post: 04-20-2002, 09:51 AM