Job Interview: What's Wrong With this Code?
by Curtis Krauskopf
Good programming problems test more than just the language's
syntax. Many programmers are also drawn toward interesting
programming puzzles.
Gimpel Software
creatively markets their C/C++ Lint tool (called PC-Lint)
by publishing a new "Bug
of the Month" in every issue of C/C++ User's Journal
and Dr. Dobbs Journal. For example, "Bug
of the Month" number 750 was published in January
of 2006:
The New Year's celebration was marred by the lack of ice for the drinks. The compiler made no complaint. Can you discover the problem?
1 #include <stdio.h>
2
3 #define ON_THE_ROCKS
4
5 const char *ice()
6 {
7 #if defined(Shaken)
8 return "shaken not stirred";
9 #elif defined(Stirred)
10 return "stirred not shaken";
11 #elif defined(ON_THE_R0CKS)
12 return "on the rocks";
13 #else
14 return "";
15 #endif
16 }
17
18 int main()
19 {
20 printf( "Celebrate the New Year " );
21 printf( "with your drink %s.\n", ice() );
22 return 0;
23 }
|
Here are two other programming snippets to puzzle over.
Neither one of these was a Gimpel.com "Bug of the
Month", but they are typical of the types of programming
problems given during C++ job interviews.
#1) What is wrong with this code?
enum ResponseType { ReturnValues, InvalidInput };
string CreateWebText(string userInput, ResponseType operation) {
switch (operation) {
case ResponseType.ReturnValues:
userInput = "<h1>Values</h1>" + FilterOutBadStuff(userInput);
break;
case ResponseType.InvalidInput:
userInput = "<h1>Invalid</h1>" + FilterOutBadStuff(userInput);
break;
}
return userInput;
}
|
#2) What is wrong with this code?
struct Fred {
Fred(int n): v(n) {}
std::vector<int> v;
};
int main() {
using namespace std;
Fred f(1);
f.v[0] = 5;
cout << f.v[0] << endl;
f = 7; // is this legal?
cout << f.v[0]; // what is output here?
}
|
|