Monday, July 22, 2013

Throwing an exception to the dog

Q: Where's my terminal?

A: It's gone. Throw a dog ate my terminal exception.

Q: Throw a dog?

A: No, throw the exception to the dog. Then it will catch it and finally bring it back to you.

Q: Dogs don't usually do that.

A: That's the whole point. Dogs don't usually do that, but there are exceptions.

Wednesday, July 17, 2013

Printing an int in C++

Q: How do you print an integer to standard output in C++?

A: Like this!

printf("%d", x);

Q: Please use C++ facilities.

A: Sure.

std::cout << x;

Q: But what if someone switched the stream to hex mode before calling your code?

std::cout << std::hex;

Then your code will print "a" instead of "10", which is not what you want.

A: Okay, I'll switch the stream to decimal mode, just to be sure:

std::cout << std::dec << x;

Q: Now your code has an unintended side effect, it might change the state of the stream for the next caller.

A: Hmm. So I need to restore the stream to its previous state, whatever it was? Hang on, I'll check the internet...

(a minute later)

Wow. There's a Boost library to do that.

Q: Seriously?

A: You know what, I'd like to go back to my first answer with printf.