Thread: is this simple program correct? K&R 1-12

Hybrid View

Previous Post Previous Post   Next Post Next Post
  1. #1
    Registered User fsx's Avatar
    Join Date
    Apr 2009
    Posts
    29
    Thanks a lot! What I would like to understand is why if I use the && it doesn't works... shouldn't it be similar to another IF statement?

    Quote Originally Posted by matsp View Post
    What is not working?

    I would expect that you will need a nested if-statement:
    Code:
       if (c == ' ' || c == '\t')
       {
         if (pc != c)
           putchar('\n');
       }
       else 
           putchar(c);
    This will prevent multiple spaces from giving multiple newlines.

    --
    Mats

  2. #2
    Kernel hacker
    Join Date
    Jul 2007
    Location
    Farncombe, Surrey, England
    Posts
    15,677
    Because you do not want the ELSE part to be executed if the second if is false - only if the first if is false.

    You could of course add a "if (pc != c)" inside the else-branch instead, but that's less logical.

    --
    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.

  3. #3
    Registered User fsx's Avatar
    Join Date
    Apr 2009
    Posts
    29
    Quote Originally Posted by matsp View Post
    Because you do not want the ELSE part to be executed if the second if is false - only if the first if is false.

    You could of course add a "if (pc != c)" inside the else-branch instead, but that's less logical.

    --
    Mats
    Mats got exactly what I was looking for, a simple explanation. I'm new to C and all those pointers, includes and so on are totally alien to my current knowledge. But thanks also for the other answerers.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Simple Blackjack Program
    By saber1357 in forum C Programming
    Replies: 1
    Last Post: 03-28-2009, 03:19 PM
  2. fopen();
    By GanglyLamb in forum C Programming
    Replies: 8
    Last Post: 11-03-2002, 12:39 PM
  3. Help with a troublesome C++ program
    By Kristina in forum C++ Programming
    Replies: 4
    Last Post: 05-18-2002, 01:28 PM
  4. Need help with simple DAQ program
    By canada-paul in forum C++ Programming
    Replies: 12
    Last Post: 03-15-2002, 08:52 AM
  5. Can't figure out why?
    By kwigibo in forum C Programming
    Replies: 10
    Last Post: 10-14-2001, 10:58 PM