ak wrote:
Recently at an interview i was asked the following question :
Assuming the function lookupName is defined, what's wrong with this
code (hint: 2 bugs)?
I'm presuming the required headers were omitted for brevity (which,
generally in interviews they are since the focus is primarily on the
code syntax and/or logic).
>
const char *getName(const char *c) {
std::string name = lookupName(c);
(1) std::string is not a valid statement in C.
if (name == NULL)
return "Anonymous" ;
return name.c_str();
(2) Technically speaking you would generally receive the diagnostic
"Request for member not in a struct or union" or something similar since
"name" was not declared. Regardless of the diagnostic message this is,
in fact, the second error that the interviewer was looking for.
}
int main(int argc, char *argv[]) {
const char *name = NULL, *c = NULL;
if (argc >= 2)
c = argv[1];
name = getName(c);
printf("My name is %s\n", name);
return 0;
}
MY SOLUTION : #bug 1: name==NULL is illegal
How so? You're comparing a pointer to NULL which is perfectly legal.
>
#bug 2: name=getName(c) should be included in
the 'if' statement so that NULL will
not be
passed to getName()
Why? Both of the following statements would yield the same results,
however the first one is most certainly easier to maintain and read:
if (name == NULL)
{
/* code here */
}
if ((name = getName(c)) == NULL)
{
/* code here */
}
Note the additional set of parentheses around the function call. Passing
a NULL value to a function /shouldn't/ be an issue provided that the
function were written to handle NULL values (as it should).
>
The above was my solution...what do you all experts think?
I'm no expert, but I know my way around the language and I'll offer my
two cents. Whether you choose to listen or not is another story, however.
Am i right or have i missed something?
Cheers,
ak
No, you are not right and yes you have missed something. In fact you
have missed many "something" 's. I strongly suggest that you study the
language in more detail before attempting to apply for another position
in your chosen field. I realize that you did not write the above
fragment of code, however you also didn't analyze it correctly either.
Some interesting topics to focus on would be operator precedence,
general logic, as well as familiarizing yourself with the standard C
library and learning the keywords used in the language. Once you are
comfortable with these topics you could then focus on reading and
writing code. Pointers are also another area that you should focus on,
however I think that you should first get a grasp on the fundamentals of
the language (and programming in general, really).