0

Reading really long functions can be very fun!

int crazylongfun()
{
  int x = -1;
  foo b = -42;

//... 1000 lines below

  if( b<-x)
  {
    std::printf("How did I get here there is no left arrow operator?\n");
  }

  return 0;    
}

Looking at foo definition

struct foo
{
  int  x;

  foo(int a) : x(a) {}

  operator int() const
  {
    return x;
  }
};

This compiles just fine and produces the desired output. What is the mechanism that allows this?

g24l
  • 3,055
  • 15
  • 28

3 Answers3

5

It's simply, "less than negative X".

if (b < -x)

After 1,000 lines I'd be kinda cross-eyed, too!

Graham Perks
  • 23,007
  • 8
  • 61
  • 83
3

Arguably implicit conversion operators in c++ are controversial, e.g. Are implicit conversions good or bad in modern C++?. When they are defined there can be very interesting syntactical situations to the unaware programmer. The above is just an example.

Here is how this works:

Struct foo has a conversion operator defined and therefore it is convertible to int which causes it to be implicitly converted and compared to the local variable x for less than minus x.

The code is actually:

if(int(b)<(-x))

i.e. There is no left arrow operator <- in c++ .

Community
  • 1
  • 1
g24l
  • 3,055
  • 15
  • 28
3

What does operator <- do in c++?

It's actually not an operator (in contrast to ->, which is one).

As mentioned in the other answers, there are in fact two operator functions applied:

  1. Unary operator-() applying a negative sign to the value
  2. Less comparison operator<()
πάντα ῥεῖ
  • 1
  • 13
  • 116
  • 190