I don't know if it's an error from C++ or not.
Try this two codes: I tried to compare two string "a" and "adnan", in two codes, it giving me two different outputs, where the second one is correct.
#include<bits/stdc++.h>
using namespace std;
int main()
{
// cout<<("a">"adnan")<<endl;
cout<<("a"> "adnan" ? "a": "adnan")<<endl;
}
/* The output is:
a
which is incorrect.
*/
and
#include<bits/stdc++.h>
using namespace std;
int main()
{
cout<<("a">"adnan")<<endl;
cout<<("a"> "adnan" ? "a": "adnan")<<endl;
}
/* the output is:
0
adnan
*/
which is correct.
I tried from different compilers I've tested it from codechef's compiler also: c++ 14, from ideone: C++, C++ 14
And found the same error. let me know reason please.
Auto comment: topic has been updated by Mr.Adnan (previous revision, new revision, compare).
Auto comment: topic has been updated by Mr.Adnan (previous revision, new revision, compare).
Auto comment: topic has been updated by Mr.Adnan (previous revision, new revision, compare).
You should typecast first.
Something like this,
cout << (((string)"a"> (string)"adnan") ? "a": "adnan") << endl;
Why typecast is needed? isn't it string by default? can you provide me any links to know more?
String comparison works in stl only. How you be sure that compiler detect your input as stl string?
okay! Thank you
Wait, but why the second one is working?!
You have to convert it into a string type before comparing with one another.
string a = "a"; string adnan = "adnan"; cout << (a > adnan ? a : adnan) << endl;
It should provide your desired output.
okay! Thank you! :D
"a" and "adnan" are not variables , so by comparing them there may occur some undefined behaviour ..
Got it! Thanks!
But the second one is working, and it is the same as previous, right?
The problem name describes it all "Undefined behaviour".
"a" and "adnan" are the constants of type
const char[N]
, that means they are arrays of chars. When you try to compare arrays, they are treated as pointers to the first element of the array (akaconst char*
), that means that they are compared by value of address, where array is stored. But result of such comparison is unspecified by standard. Read this answer if you want to know more about that https://stackoverflow.com/a/9086675 .wow! thank you so much! Understood it. thanks again.