It is well known — and intuitively understood by most — that adding a set of parentheses usually doesn’t change anything; for example, int answer = 42; is equal to int answer = (42); or int answer = ((42));. There are some important exceptions to that rule, however, and I’ll talk about these in this post.
Although macros are rarely used in good C++ code, it is important to be able to understand what’s happening and why. Using a popular example of MIN macro, the naïve implementation would look like this:
#define MIN(x,y) x < y ? x : y
To a beginner, this would look like a correct implementation, and indeed, it would work in some cases; for example, answer below would indeed be equal to 42:
Unfortunately, macros are expanded as text, and in the following example, possibly surprisingly, answer would hold the value of 41 instead:
int answer = 2 + MIN(40,41);
Consider the following code:
using namespace std;
int n = 10;
while(n --> 0)
cout << "n: " << n << endl;
Should it compile? If your answer is yes, what should be its output?
Some men just want to watch the world burn. Some of them are teacher assistants. And some of them give tests like
this to an intro class. Sure, it’s not very difficult (except for 1e, which requires deeper understanding of the language), but it’s really, really tricky.
Well, check for yourself.
Easily findable link:
Many programmers new to C++, especially those coming from languages that focus on programmer productivity instead of performance per Watt, are surprised by the fact that one cannot use the switch statement with anything other than constant integers, enums or classes that have a single non-explicit integer or enum conversion operator. It’s a fairly reasonable concern – after all, there are lots of use cases for such a feature.
With the introduction of constexpr in C++11 last year it could be expected that such expressions of any type would become legit expression for the case label, but alas, they aren’t. That being said, it’s not impossible to do – at least in some form – or I wouldn’t be writing this post. With use of two very nifty C++11 features a very similar result can be achieved.
Over the last month and a half* one of the things I’ve been tasked with was removing memory leaks from our software. At first, it looked like as if I was presented with a daunting responsibility, with the VLD spewing several thousands of apparent memory leaks after just a sample test-run of our main program. Fortunately for me, the vast majority of the leaks seemed to originate from three interface classes.