Skip to content

Caught, time and again

Is the solution to this apparent to you?

Given this piece of C++ code:

  // definitions (a and b are primitive types)
  a = b+1;
  if (a == b+1) cout<<"True";
  else cout<<"False";

Under what conditions would the code print "False"?

The answer, when I finally get it, is obvious, but I manage to forget it every time and repeatedly fall into this trap.


  1. Soham wrote:

    Whats the answer man ? Is it when b is something like 32767 and a overflows and becomes 0 ?

    Monday, October 30, 2006 at 12:14 pm | Permalink
  2. Anshul wrote:

    That may be possible, but this can arise due to a more conceptual error – when a and b are referenced to each other (point to the same memory location). So if you define a and b as:

    int a = 1;
    int& b = a;

    you’ll get this behavior.

    Monday, October 30, 2006 at 12:21 pm | Permalink

Post a Comment

Your email is never published nor shared.