string equality testing

This is a discussion on string equality testing within the C Programming forums, part of the General Programming Boards category; Can I do... Code: char first[10] = "123456789"; char second[10] = "123456789"; if (first == second) { printf("The strings are ...

  1. #1
    Registered User
    Join Date
    Feb 2009
    Posts
    278

    string equality testing

    Can I do...

    Code:
    char first[10] = "123456789";
    char second[10] = "123456789";
    
    if (first == second) {
      printf("The strings are the same");
    } else {
      printf("The strings are not the same");
    }

  2. #2
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    23,796
    Yes, but you actually want to use say, strcmp().
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  3. #3
    Registered User hk_mp5kpdw's Avatar
    Join Date
    Jan 2002
    Location
    Northern Virginia/Washington DC Metropolitan Area
    Posts
    3,815
    In the context you've mentioned above, the expression testing for equality is actually comparing the address of the two variables ("first" and "second"). The address of these two distinct variables will never be the same. In C++ using std::string containers you can test the variables as you've done but in C you need the strcmp function.
    "Owners of dogs will have noticed that, if you provide them with food and water and shelter and affection, they will think you are god. Whereas owners of cats are compelled to realize that, if you provide them with food and water and shelter and affection, they draw the conclusion that they are gods."
    -Christopher Hitchens

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Please check my C++
    By csonx_p in forum C++ Programming
    Replies: 263
    Last Post: 07-24-2008, 09:20 AM
  2. Compile Error that i dont understand
    By bobthebullet990 in forum C++ Programming
    Replies: 5
    Last Post: 05-05-2006, 09:19 AM
  3. Calculator + LinkedList
    By maro009 in forum C++ Programming
    Replies: 20
    Last Post: 05-17-2005, 12:56 PM
  4. lvp string...
    By Magma in forum C++ Programming
    Replies: 4
    Last Post: 02-26-2003, 11:03 PM

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