Why can't i compare characters like this?

This is a discussion on Why can't i compare characters like this? within the C Programming forums, part of the General Programming Boards category; Why can't i compare characters like this? thnx Code: #include <stdio.h> int main() { char c = 'X'; char c2 ...

  1. #1
    Registered User Nutshell's Avatar
    Join Date
    Jan 2002
    Posts
    1,020

    Why can't i compare characters like this?

    Why can't i compare characters like this?

    thnx

    Code:
    #include <stdio.h>
    
    int main()
    {
       char c = 'X';
       char c2 = 'X';
       char c3 = 'X';
    
       if ( c == c2 == c3 )
          printf( "Compared successfully" );
    
       system("PAUSE");
       return 0;
    }

  2. #2
    &TH of undefined behavior Fordy's Avatar
    Join Date
    Aug 2001
    Posts
    5,789
    Here's a clue

    Code:
    int main()
    {
       char c = 'X';
       char c2 = 'X';
       int c3 = 1;//What!!!!!
    
      if ( c == c2 == c3 )
          printf( "Compared successfully" );
    
       system("PAUSE");
       return 0;
    }

  3. #3
    Registered User Nutshell's Avatar
    Join Date
    Jan 2002
    Posts
    1,020
    In your example, it will return false, according to my theory, but in my example, it'll return true. But sinze that's not the case, i don't know what's wrong with it.

    I hope you can explain.

    thnx

  4. #4
    Registered User Nutshell's Avatar
    Join Date
    Jan 2002
    Posts
    1,020
    Wait, i think i got it.

    When i compare this:

    c == c2

    if they are equal they return 1, indicating true,

    when it's compared to c3 like this

    c2 == c3,

    it's actually comparing c3 with 1 like

    c3 == 1


    am i right this time?

    thnx

  5. #5
    &TH of undefined behavior Fordy's Avatar
    Join Date
    Aug 2001
    Posts
    5,789
    You win the prize!

  6. #6
    Registered User
    Join Date
    Mar 2002
    Posts
    17
    So, to do what he wants to do it would be

    Code:
    if (ch1==ch2 && ch2==ch3)
    ....
    right?

  7. #7
    Registered User Nutshell's Avatar
    Join Date
    Jan 2002
    Posts
    1,020
    yea

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. A development process
    By Noir in forum C Programming
    Replies: 37
    Last Post: 07-10-2011, 10:39 PM
  2. problem with compare two characters
    By Martin Kovac in forum C Programming
    Replies: 1
    Last Post: 04-09-2009, 12:45 PM
  3. Replies: 10
    Last Post: 07-10-2008, 03:45 PM
  4. Replies: 7
    Last Post: 05-11-2008, 10:57 AM
  5. Using if statments to compare characters
    By rakan in forum C++ Programming
    Replies: 2
    Last Post: 01-30-2006, 12:11 PM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21