Thread: K & R exercise - which code would you prefer?

  1. #1
    Registered User
    Join Date
    May 2011
    Posts
    32

    K & R exercise - which code would you prefer?

    Hello,

    I tried to code one of the exercises in K&R, namely the one in which you are supposed to read the input and output it one word per line.

    I've come up with two functions, the only difference being in the else block. I think the else block in the first function shows better coding practice (the variable "state" gets changed only when necessary) whereas in the second function it is more compact.

    Which of those two functions would you choose?

    I tried googling this exercise and most sample answers prefer the second example, which surprises me.

    Code:
    #include <stdio.h>
    
    #define IN   1  /* inside a word */
    #define OUT  0  /* outside a word */
    
    void output1()
    {
        int c, state;
        state = OUT;
        while ((c = getchar()) != EOF) {
            if (c == ' ' || c == '\n' || c == '\t')
            {
                if (state == IN)
                {
                    putchar('\n');
                    state = OUT;   
                }
            }
            else
            {
                if (state == OUT)
                    state = IN;
                putchar(c);
            }
        }
    }
    
    void output2()
    {
        int c, state;
        state = OUT;
        while ((c = getchar()) != EOF) {
            if (c == ' ' || c == '\n' || c == '\t')
            {
                if (state == IN)
                {
                    putchar('\n');
                    state = OUT;   
                }
            }
            else
            {
                state = IN;
                putchar(c);
            }            
        }
    }

  2. #2
    Banned
    Join Date
    Aug 2010
    Location
    Ontario Canada
    Posts
    9,547
    The if(state ==OUT) decision in the first one is entirely unnecessary and thus not better practice...
    The code has only two states thus if it's not IN, it has to be OUT...

    While it's not terribly likely in this code sample... consider what might happen if state somehow got changed to 2 instead of just 0 and 1...
    Last edited by CommonTater; 08-17-2011 at 03:37 PM.

  3. #3
    and the Hat of Guessing tabstop's Avatar
    Join Date
    Nov 2007
    Posts
    14,336
    I think you've got the else going to the wrong if there, Tater.

    The first one is in theory less efficient, as the if will take longer than the assignment regardless of whether the assignment is necessary. Technically the same is true of the first one, but there the logic is different so you have to do the check anyway.

  4. #4
    Banned
    Join Date
    Aug 2010
    Location
    Ontario Canada
    Posts
    9,547
    Quote Originally Posted by tabstop View Post
    I think you've got the else going to the wrong if there, Tater.

    The first one is in theory less efficient, as the if will take longer than the assignment regardless of whether the assignment is necessary. Technically the same is true of the first one, but there the logic is different so you have to do the check anyway.
    Go ahead... set state = 3 and watch what happens...

  5. #5
    Registered User
    Join Date
    May 2011
    Posts
    32

    Smile

    Quote Originally Posted by CommonTater View Post
    Go ahead... set state = 3 and watch what happens...
    Why would one want to do that in the first place? :-)

    How would you improve the code then, please?

    I tried to write two pieces of code that would be clean, readable and as much "textbook-like" as possible, where did I fail then?

    Thanks in advance for your answers,

    Caroline

  6. #6
    ATH0 quzah's Avatar
    Join Date
    Oct 2001
    Posts
    14,826
    Code:
    void Q_Q( void )
    {
        int c, state = OUT;
        while ((c = getchar()) != EOF)
        {
            switch( c )
            {
                case ' ':
                case '\n':
                case '\t': c = '\n';
                default:
                    state = c == '\n' ? OUT : IN;
                    putchar( c );
            }
        }
    }
    I think that will do the same thing.


    Quzah.
    Hope is the first step on the road to disappointment.

  7. #7
    Banned
    Join Date
    Aug 2010
    Location
    Ontario Canada
    Posts
    9,547
    Quote Originally Posted by kkk View Post
    Why would one want to do that in the first place? :-)

    How would you improve the code then, please?

    I tried to write two pieces of code that would be clean, readable and as much "textbook-like" as possible, where did I fail then?

    Thanks in advance for your answers,

    Caroline
    Because it's an error condition... it's just as important to see how a program screws up as it is to get it running in the first place... You'll be amazed what you can learn watching something crash and burn...

  8. #8
    ATH0 quzah's Avatar
    Join Date
    Oct 2001
    Posts
    14,826
    Quote Originally Posted by CommonTater View Post
    You'll be amazed what you can learn watching something crash and burn...
    We've learned a LOT from Tater!


    Quzah.
    Hope is the first step on the road to disappointment.

  9. #9
    Banned
    Join Date
    Aug 2010
    Location
    Ontario Canada
    Posts
    9,547
    Quote Originally Posted by quzah View Post
    we've learned a lot from tater!
    quzah.
    sigh

  10. #10
    ATH0 quzah's Avatar
    Join Date
    Oct 2001
    Posts
    14,826
    Dear dude,

    Don't lower case me! That's an insult in these here parts!


    Quzah.
    Hope is the first step on the road to disappointment.

  11. #11
    Registered User
    Join Date
    May 2011
    Location
    Around 8.3 light-minutes from the Sun
    Posts
    1,949
    Quote Originally Posted by quzah View Post
    Dear dude,

    Don't lower case me! That's an insult in these here parts!


    Quzah.
    Careful, quzah...them are fightin' words where Tater comes from.
    Quote Originally Posted by anduril462 View Post
    Now, please, for the love of all things good and holy, think about what you're doing! Don't just run around willy-nilly, coding like a drunk two-year-old....
    Quote Originally Posted by quzah View Post
    ..... Just don't be surprised when I say you aren't using standard C anymore, and as such,are off in your own little universe that I will completely disregard.
    Warning: Some or all of my posted code may be non-standard and as such should not be used and in no case looked at.

  12. #12
    ATH0 quzah's Avatar
    Join Date
    Oct 2001
    Posts
    14,826
    Your location always makes me wonder if that's how they came up with the length for DOS file names.

    This thread has been successfully highjacked.


    Quzah.
    Hope is the first step on the road to disappointment.

  13. #13
    Registered User
    Join Date
    May 2011
    Location
    Around 8.3 light-minutes from the Sun
    Posts
    1,949
    Quote Originally Posted by quzah View Post
    Your location always makes me wonder if that's how they came up with the length for DOS file names.
    Haha...chances are. Those guys were completely crazy back then.

    Quote Originally Posted by quzah View Post
    This thread has been successfully highjacked.
    It was going to happen sooner or later, topics like this one lend themselves to be hijacked.
    Quote Originally Posted by anduril462 View Post
    Now, please, for the love of all things good and holy, think about what you're doing! Don't just run around willy-nilly, coding like a drunk two-year-old....
    Quote Originally Posted by quzah View Post
    ..... Just don't be surprised when I say you aren't using standard C anymore, and as such,are off in your own little universe that I will completely disregard.
    Warning: Some or all of my posted code may be non-standard and as such should not be used and in no case looked at.

  14. #14
    Registered User
    Join Date
    May 2011
    Location
    Around 8.3 light-minutes from the Sun
    Posts
    1,949
    Quote Originally Posted by quzah View Post
    Code:
    void Q_Q( void )
    {
        int c, state = OUT;
        while ((c = getchar()) != EOF)
        {
            switch( c )
            {
                case ' ':
                case '\n':
                case '\t': c = '\n';
                default:
                    state = c == '\n' ? OUT : IN;
                    putchar( c );
            }
        }
    }
    I think that will do the same thing.


    Quzah.
    Perhaps this....
    Code:
    void O_o(int state){
    	int c;
    	if( (c=getchar())!=EOF){
    		if(isspace(c)) c='\n';
    		putchar(c);
    		O_o(c=='\n' ? OUT:IN);
    	}
    }
    Quote Originally Posted by anduril462 View Post
    Now, please, for the love of all things good and holy, think about what you're doing! Don't just run around willy-nilly, coding like a drunk two-year-old....
    Quote Originally Posted by quzah View Post
    ..... Just don't be surprised when I say you aren't using standard C anymore, and as such,are off in your own little universe that I will completely disregard.
    Warning: Some or all of my posted code may be non-standard and as such should not be used and in no case looked at.

  15. #15
    ATH0 quzah's Avatar
    Join Date
    Oct 2001
    Posts
    14,826
    Honestly at this point, I'm not even sure why we are still using the state variable.


    Quzah.
    Hope is the first step on the road to disappointment.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. which way you prefer
    By l2u in forum C++ Programming
    Replies: 4
    Last Post: 06-07-2007, 11:39 AM
  2. What do you prefer??
    By girlzone in forum A Brief History of Cprogramming.com
    Replies: 29
    Last Post: 05-21-2003, 01:03 AM
  3. Which do you prefer?
    By face_master in forum A Brief History of Cprogramming.com
    Replies: 12
    Last Post: 09-24-2002, 05:35 PM
  4. Which OS do you prefer?
    By Golden Bunny in forum A Brief History of Cprogramming.com
    Replies: 32
    Last Post: 05-29-2002, 02:34 PM
  5. what do you prefer
    By whistlenm1 in forum A Brief History of Cprogramming.com
    Replies: 6
    Last Post: 01-28-2002, 09:27 PM