1

I'm learning C++ with previous Java experience.I found the following example in the cplusplus.com :

int CDummy::isitme (CDummy& param)
{
  if (&param == this)
  { 
       return true; //ampersand sign on left side??
  }
  else 
  {    
       return false;
  }
}

My question is : Why does it return boolean false when I clearly declared the method as int ? It's never possible in Java. The link of the example is : here.

12
  • 5
    @KeithThompson - The author is writing crap code IMHO Commented Jul 19, 2016 at 23:00
  • 6
    I wouldn't trust an example that takes so long to say return &param == this;. Commented Jul 19, 2016 at 23:00
  • 1
    Perhaps historical reasons? Very early versions of C++, and versions of C prior to C99, didn't have a bool type, so int was commonly used to represent boolean values (0 for false, anything else (especially 1) for true). That's no excuse for writing code like that for a C++ reference site. Commented Jul 19, 2016 at 23:03
  • 1
    @SittingBull I can feel with you. There are much better and reliable resources available than cplusplus.com actually. Commented Jul 19, 2016 at 23:12
  • 1
    @SittingBull You might be interested in reading this post. Commented Jul 19, 2016 at 23:16

2 Answers 2

8

While the question of why the function does what it does is best answered by the author of the function, it is easy to explain why C++ allows such function to compile without a problem.

In C++ bool is a fundamental integral type, so it can be freely converted to a number: true becomes 1, and false becomes zero.

Sign up to request clarification or add additional context in comments.

Comments

0

This is just an instance of implicit conversion. In c++, 1 and true (also 0 and false) are the same thing(s).

You could also do something like

while (1)
   //Infinite loop

or

bool b = false;
if (b == 0) {
    //This is reached
}
else {
    //This is not
}

2 Comments

(Java is a bit less messy here, but the second example would afaik also work.)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.