Thread: Function converting from 1-7 for days of the week to actual strings

Threaded View

Previous Post Previous Post   Next Post Next Post
  1. #4
    Algorithm Dissector iMalc's Avatar
    Join Date
    Dec 2005
    Location
    New Zealand
    Posts
    6,318
    Quote Originally Posted by Elysia View Post
    That only works if days is a global variable; otherwise you're returning the address of a local variable, assuming that a function is returning that information.
    In which case, it would be more efficient to make the function take a buffer and size, do a switch and copy the appropriate string into the buffer.
    Well it would be fine if this was the C++ forum, because the return type would then probably be std::string. However being C there's still nothing stopping us from doing it the preferred way, using a lookup table.
    Code:
    // Preconditions:
    // inDayIndex is between 1 and 7
    // outDayName points to a buffer big enough to hold at least 10 characters
    void getDayOfWeekName(int inDayIndex, char *outDayName)
    {
        static const char days[7][] =
            { "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday" };
        strcpy(outDayName, days[inDayIndex - 1]);
    }
    Don't use a switch where an explicit lookup table will work.
    A switch is not more efficient. It is at best just as efficient, provided it happens to optimise down to a jump table. You're better off implementing it directly as a table on your own.
    Last edited by iMalc; 12-31-2007 at 01:34 PM.
    My homepage
    Advice: Take only as directed - If symptoms persist, please see your debugger

    Linus Torvalds: "But it clearly is the only right way. The fact that everybody else does it some other way only means that they are wrong"

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 4
    Last Post: 05-13-2011, 08:28 AM
  2. Getting an error with OpenGL: collect2: ld returned 1 exit status
    By Lorgon Jortle in forum C++ Programming
    Replies: 6
    Last Post: 05-08-2009, 08:18 PM
  3. Compiling sample DarkGDK Program
    By Phyxashun in forum Game Programming
    Replies: 6
    Last Post: 01-27-2009, 03:07 AM
  4. We Got _DEBUG Errors
    By Tonto in forum Windows Programming
    Replies: 5
    Last Post: 12-22-2006, 05:45 PM
  5. Programming using strings
    By jlu0418 in forum C++ Programming
    Replies: 5
    Last Post: 11-26-2006, 08:07 PM