Home > Uncategorized > Pop quiz

Pop quiz

May 4th, 2009 — Mark Przepiora

All right, class. Who can tell me what the following program will output? Bear with me, I promise this gets interesting.

1
2
3
4
5
6
int main ()
{
  int x = 0, y = 0;
  y = ++x + 10;
  printf("%d, %d\n", x, y);
}

That’s easy, it’s exactly what you expect: “1, 11″.

What about if you replace line 4 with the following?

y = x++ + 10;

Again, easy! This time, the expression x++ evaluates to the value of x before it is incremented, so the answer is “1, 10″.

Now, what about this?

1
2
3
4
5
6
int main ()
{
  int x = 0;
  x = ++x + 10;
  printf("%d\n", x);
}

This is no different than the first example, except that we’ve chucked the variable y, so the answer is “11″.

Last question: (and I’m sure you can see where this is going) what if you replace line 4 with the following?

x = x++ + 10;

 

I’m obviously trying to trick you, so you must realize that the answer is surprisingly also “11″, but can anyone tell me why it is so?

 

Extra credit: explain what happens if you replace line 4 with this seemingly-equivalent statement:

*(&x) = (x++) + 10;

,

  1. No comments yet.
  1. No trackbacks yet.