Thread: understanding switch vs. if / else

  1. #1
    ... kermit's Avatar
    Join Date
    Jan 2003
    Posts
    1,534

    understanding switch vs. if / else

    I wrote a program that was supposed to replace an tab in the input with '\\t', any backspace with '\\b' and the backslash itself was to be replaced with '\\\'. Here is what I wrote initially:
    Code:
    #include <stdio.h>
    int main(void)
    {
         int c;
         while( ( c = getchar() ) != EOF ){
    	  if( ( c = '\t' ) ){
    	       printf( "\\t" );
    	  }
    	  else if( ( c = '\b' ) ){
    	       printf( "\\b" );
    	  }
    	  else if( ( c = '\\' ) ){
    	       printf( "\\\\" );
    	  }
    	  else
    	       putchar( c );
         }
         return 0;
    }
    Obviously it does not work the way I wanted it to. Then I wrote the same program using a switch statement:
    Code:
    #include <stdio.h>
    int main(void)
    {
         int c;
         while( ( c = getchar() ) != EOF ){
    	  switch ( c ){
    	  case '\t':
    	        printf( "\\t" );
    		break;
    	  case '\b':
    	        printf( "\\b" );
    		break;
    	  case '\\':
    	        printf( "\\\\" );
    		break;
    	  default:
    	       putchar( c );
    	  }
         }
         return 0;
    }
    The second version works correctly. Why does the first one not work? I know it will be something simple, but I am missing it totally.

    ~/

  2. #2
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,659
    > if( ( c = '\t' ) )
    Should be
    if( ( c == '\t' ) )


    and
    else if( ( c = '\' ) )
    should be
    else if( ( c == '\\' ) )
    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.

  3. #3
    ... kermit's Avatar
    Join Date
    Jan 2003
    Posts
    1,534
    Aww crap -- well that is worth a good laugh. Thanks a lot Salem. I don't think I had my head on straight this morning.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Data Structure Eror
    By prominababy in forum C Programming
    Replies: 3
    Last Post: 01-06-2009, 09:35 AM
  2. Replies: 7
    Last Post: 04-11-2008, 07:42 AM
  3. ascii rpg help
    By aaron11193 in forum C Programming
    Replies: 18
    Last Post: 10-29-2006, 01:45 AM
  4. Switch
    By cogeek in forum C Programming
    Replies: 4
    Last Post: 12-23-2004, 06:40 PM
  5. Switch Case
    By FromHolland in forum C++ Programming
    Replies: 7
    Last Post: 06-13-2003, 03:51 AM