This months Smiley's article

Electronics Computer Programming Q&A
RiJoRi
Posts: 13
Joined: Tue Aug 12, 2008 11:25 am
Contact:

Re: This months Smiley's article

Post by RiJoRi » Thu Feb 05, 2009 12:50 pm

Chupa wrote:Smiley's article in this months is about makeing a Nav menu in C. He joked in the article saying that some users would probably laugh at his method of using a state machine and a ton of switch statements which made me wonder if theirs a better way to do it, even if it is more complex.
There is. I just looked at it again. I did NOT write this, and it is just code fragments.

Code: Select all

struct dtable
{
    union
    {
        struct
        {
            unsigned char len;
			char word[3];
        } bytes;
        unsigned long bits;
    }id;
    void (*func)();
};

#define ENTRIES 5
/* All the names (dot, store, etc. are the names of functions which must be added. */
struct dtable dictionary[ENTRIES] =
{
    {1, '.',  0 ,  0 , dot   },    /*  1 */
    {1, '!',  0 ,  0 , store },    /*  2 */
    {1, '@',  0 ,  0 , at    },    /*  3 */
    {1, '?',  0 ,  0 , query },    /*  4 */
    {1, '+',  0 ,  0 , plus  }     /*  5 */
};

void main(void)
{
    unsigned long ident;
    unsigned int match,error;
    unsigned int i,j;
    struct dtable scratch;

    while(1)
    {
        gets(str);
	tok = strtok(str," ");
        if (tok)
		do
		{
                	scratch.id.bytes.len = (unsigned char) strlen(tok);
	                for (i=0; i<3; i++)
        	            if(i<strlen(tok))
                	        scratch.id.bytes.word[i] = (char)tolower(tok[i]);
	                    else
        	                scratch.id.bytes.word[i] = 0;
		        ident = scratch.id.bits;
		        match = 0;
/* The non-switch function selector */
	                for (i=0; i<ENTRIES && !match; i++)
        	        {
                    		if (ident == dictionary[i].id.bits)
		                {
                        		match = 1;
                        		(*dictionary[i].func)();
                    		}
                	}
/* More code was here */

	            } while ((tok = strtok(NULL," ")) && !error);
        }
}
I think I prefer switch statements!

FWIW, Python (unlike some modern BASICs) does not have a switch-type statement; it has an "elif" keyword for the same effect.

--Rich

Post Reply

Who is online

Users browsing this forum: No registered users and 3 guests