-1

Whenever I run this in the compiler I get 1 returned to me. However, I've been told that this shouldn't return 1 and that my compiler is wrong and can't be trusted.

Is my friend right in that the compiler's I use are giving me the incorrect answer, or is this supposed to return 1?

#include <iostream>
#include <string>

int main()
{
    bool lol = "abc" < "abcd";
    std::cout << lol;
    return 0;
}
big smash
  • 9
  • 1
  • 2
    You compare pointers to those strings locations. Formally that's undefined behaviour. You probably want to use `std::strcmp()` or `std::string`s instead. – HolyBlackCat Jul 15 '18 at 19:48
  • If your compiler returns `1`, there is something gone wrong during compilation. The compiler does not execute the source code, but … well … compiles it. – too honest for this site Jul 15 '18 at 19:58

1 Answers1

2

The code has Undefined Behaviour, because it's using an oredering comparison operator on two pointers (the address of the string literal "abc" and that of the string literal "abcd") which are not part of the same array. It can therefore do absolutely anything.

Angew is no longer proud of SO
  • 167,307
  • 17
  • 350
  • 455