0

Why is the output of the following codes different?

I'm comparing two strings. I don't understand why they give different outputs?

Code 1:

#include <bits/stdc++.h>
using namespace std;

int main() {
    if("35" <= "255")
    {
        cout << 1;    
    }
    cout << 0;
}

Code 2:

#include <bits/stdc++.h>
using namespace std;
int main() {
    string num = "35";
    if(num <= "255")
    {
        cout << 1;    
    }
    cout << 0;
}

The output of code 1 is 10. The output of code 2 is 0.

Alexander Chernin
  • 446
  • 2
  • 8
  • 17

3 Answers3

3

You made the second program different by using std::string.

std::string has an overload for the comparison operator, which compares the content of the operands lexicographically. Lexicographical ordering, which is different from numerical ordering, is same that would be used in a dictionary: 255 comes before (i.e. "is less than") 35, just like aardvark comes before zoo.

The string literals on the other hand are arrays, which will decay to a pointer to first element, and pointer comparison compares the relative location in memory, which has nothing to do with the text content, and which in this case is at best unspecified and you could either see 1 output or not.

eerorika
  • 232,697
  • 12
  • 197
  • 326
0

A string is not a magic object that understands what it contains and acts differently on it.

In your case, you are comparing the address that hold a buffer of chars (containing '3', '5', 0) with the address containing another buffer of chars (containing '2', '3', '5', 0).

The output is random (in fact, it isn't, but for now, let's assume it is).

If you want to compare strings, you can use the second example (or strcmp) but that will compare the buffer content based on some logical rules, that are not those you except (you expect semantic logic, but it's not).

The rules are:

  1. Compare each buffer char based on their ASCII/Unicode order, and return -1 if the first one is lower than the second one, 1 if it's higher. (If using < operator, it returns true if -1, false otherwise and so on)
  2. If they are equal, continue to next char.

In the previous example, '3' is higher than '2' (even if 35 is smaller than 235).

You'll need to either convert your string to integer before comparing (and deal with potential conversion errors) or use integers from the beginning.

xryl669
  • 3,376
  • 24
  • 47
0

First convert the string to Int and then compare.

Example:

#include <iostream>
using std::cout;

string value1 = "22";
string value2 = "222";
int main()
{
if(std::stoi(value1)<=std::stoi(value2)) 
{

cout<<"1";

}
cout<<"0";


}
Pradeep Kumar
  • 109
  • 1
  • 10