gbadev.org forum archive

This is a read-only mirror of the content originally found on forum.gbadev.org (now offline), salvaged from Wayback machine copies. A new forum can be found here.

C/C++ > Basic C++ help

#116011 - Dox-999 - Sun Jan 21, 2007 3:29 am

Hi guys, I am new to C++ and I have recently started doing some tutroials, when I work I like to fully understand things before I move on and what I don't understant is how to use "&&" and "||" with integers.

I have done it fine with strings before:
Code:
if (password == "hello" || "world") {


but I want to be able to do lines like this:
Code:
if (age >= 21 && < 100) {


How can I do this?

Thanks :)

#116012 - gmiller - Sun Jan 21, 2007 3:33 am

Simple:

Code:


if ((age >= 21) && (age < 100)) {
 // Do something
}

#116013 - Dox-999 - Sun Jan 21, 2007 3:47 am

Thanks mate

#116018 - Lick - Sun Jan 21, 2007 4:56 am

Code:
if (password == "hello" ..


Warning! This is actually totally not working as you think it would! First of all, in C strings are char-pointers. You are actually comparing the pointers instead of comparing the data that's AT the pointer.
Use strcmp() to test C-strings, or avoid using C-strings and start using C++-strings. Here's an example:
Code:
#include <string.h>

int main() {
    char *password = "hello";

    if(strcmp(password, "hello") == 0) // zero differences
       bla();

    return 0;
}

#include <string>

int main() {
    std::string password("hello");
    return 0;
}

Search "std string stl" for more information on C++-strings.

---


Code:
.. || "world") {

This is actually ALWAYS true, because again - you're validating the POINTER instead of the DATA.
So even if("") should be true.
_________________
http://licklick.wordpress.com

#116023 - Dox-999 - Sun Jan 21, 2007 5:20 am

Ok thats for that :)

#116051 - Quirky - Sun Jan 21, 2007 1:00 pm

If password is a std::string and we are talking C++ then == would do what you expect since std::string::operator== uses std::string::compare rather than comparing pointers. Example:
Code:

#include <string>
#include <iostream>
using namespace std;

int main(int argc, char * argv[])
{
  string password(argv[1]);
  if (password == "hello")
  {
    cout << "Password Correct" << endl;
    return 0;
  }
  cout << "Password wrong" << endl;
  return 1;
}

Code:

g++ test.cpp -o testString
./testString hi
Password wrong
./testString hello
Password Correct


The line s1==s2 is the same as s1.compare(s2) == 0.

If we are talking C, then all of what was said previously applies. But if you are including <string>, may as well use it ;) (I don't recommend this approach as a security measure BTW :)))

#116059 - keldon - Sun Jan 21, 2007 2:58 pm

The line is faulty even if it is a string as there is an incorrect use of the || operator.