According to grammar rules defined by the C++ standard (and C as well) the following code is valid:
switch(i) i++; |
According to grammar rules defined by the C++ standard (and C as well) the following code is valid:
switch(i) i++; |
Every now and then I see people writing C++ code containing heresy in the vein of the following:
char * foo = "bar"; |
This is no more legal C++ than
const int qux = 42; int * quux = &qux; |
It is not undefined, unspecified or implementation defined! It is simply illegal
The following is a legit, albeit a little obscure, C89 program. It is also a legit C++11 (and above) program.
int main(void) { auto a = 42; return 0; } |
A new C++ quiz website has been created under the address cppquiz.org. It’s work in progress, but the quality of questions so far is excellent. I especially recommend questions number 31 and 15.
Edit: More questions of mine have been approved: 37, 38, 42 and 48.
Edit #2: adding to the recommendations: 151, 152 and 153 and 198.
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:
int answer = MIN(42,50); |
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); |