share
Stack OverflowQuestions every good C/C++ Developer should be able to answer?
[+39] [35] Mohit Jain
[2010-10-14 12:52:11]
[ c++ c interview-questions ]
[ http://stackoverflow.com/questions/3933263] [DELETED]

I was going through interview questions [1] tag and found those question are quite useful, so in the same spirit, I am asking this question for C and C++ developers

What questions do you think good C and C++ programmers should be able to answer?

Looking forward for some amazing responses.

Please answer questions too, so that people could learn something new regarding the language, too.

(9) You should set this question as community wiki. - Didier Trosset
(89) The first thing a good C/C++ programmer should know is that C/C++ isn't a language. They are two completely different languages and being good at one doesn't mean you are also good at the other. - Mark Byers
@Didier Trosset: Maybe not. That's not a poll actually - that's a real question. - sharptooth
(6) @Mark Byers: I totally agree. "The C/C++ language"? Absolute fail. - DeadMG
(1) @sharptooth Open-ended questions designed to encourage a large number of answers and discussion rather than a small number of concrete answers are ideal community wiki candidates too. - meagar
I am not able to make it community wiki.. Please check it. reported on meta stackoverflow. meta.stackoverflow.com/questions/67604/… - Mohit Jain
Adding the comment here as it applies to many answers so far: I could answer most of the alleged good C++ questions (pointers, difference between heap, stck etc), and I'm not a good C++ developer, having had very little experience with it (I'm fine on C). So the questions may need to be a bit deeper/more searching. - Paul
Any body who have more reputation. Please make this question as community-wiki. - Mohit Jain
(1) @piemesons, @all: Please go and read the question and its answers on meta to which I linked in my previous comment. - sbi
@piemesons It will automagically become CW when it rolls over ~30 answers - meagar
@meagar the link above this comment is for you as well :) - badp
If 6 different people edit it then it automatically becomes CW I think. - Martin Smith
(2) @all 2 downvotes and now a vote to close. thats insane.. - Mohit Jain
(9) You've been explained linked to the reason why this kind of question does not belong here. See, community wiki questions are no more and this is why. If you think a question needed Community Wiki, you want it closed instead. Besides, "@all" doesn't work. - badp
(2) @Byers: Yes, yes, C and C++ are not the same language. But they're obviously related. Like "British English" and "American English" are not the same language, but surely there are many valid things that can be said about both. - Jay
(4) Belongs on programmers.se - Benjol
@Benjol, in its current form it would be closed there too. "What questions do you think good C and C++ programmers should be able to answer?" - badp
(3) @Jay I would argue "C/C++" is more like "Latin/English", while "British/American English" is like "K&R/Allman style C++." Mainly, in the case of British/American, it's the same language. - meagar
(1) i was about to answer when it was closed. here are my answers: - How do you know malloc() fails? How do you know new fails? - How do you read binary files and text files? - Donotalo
(1) @badp: @all works pretty well. Whoever reads it knows it applies to them. - sbi
(1) It has been reopened, and votes to close it has begun....wow! - The Elite Gentleman
(4) Why would you want to close this question? Suppose someone searches for good interview questions and google points them to this page. It's a fairly well-asked question._ (I object to "C/C++", too, but, hey...) There can be pretty good, straightforward answers to it and the voting system will bubble up the good ones. Whoever searched will find themselves equipped with a bunch of pretty good questions to ask for their next interview. And this is exactly what SO was invented for. So why close this? - sbi
(5) @sbi - blog.stackoverflow.com/2010/09/good-subjective-bad-subjective. How many of these do you think this question has fulfilled? - Yi Jiang
(3) @sbi Not everything with a question mark can be discussed here. The system just isn't good at it. Also it's not well asked: you cannot accept an answer when you ask "what do you think". - badp
(5) @Jay: I can write a complicated essay in US English, and if it's good in US English it's good in British English. If I write a program of significant size in C++, it won't compile in C. If I write a program of significant size in idiomatic C, it may not compile in C++, and even if it does it won't be anywhere near good C++. - David Thornley
@Yi Jiang: This presumes that the question is subjective, a categorization which I object to. It's a classic Make-a-List question. - sbi
@badp: Where did I say that everything with a question mark can/should/would be discussed here? Heck, if you think I even implied this, you should read my comment again. You just knocked down a strawman. I'm not impressed and my argument still stands. - sbi
@sbi feel free to ignore the rest of what I wrote - badp
(5) Automatic -1 for "I saw other questions like this, so in the same spirit..." -- Stack Overflow is for real questions, not for groupies asking lookalike questions that aren't real questions. There are already a number of general C++ wisdom questions; we don't need another one. - Ether
"In the same spirit...." I can predict that this question (my bad...wiki) will be closed (for the 2nd time) and then reopened again.... - The Elite Gentleman
(5) Based on the answers thus far, I think this question is completely useless to anyone looking to learn something or prepare for an interview. The answers simply list topics and questions, but don't even give answers to those questions or links to resources for learning more about the topics. There are also no explanations as to why someone would need to or be expected to know about a given topic. All in all, this question is an information dead-end. - gnovice
(1) I wonder the real aim of this question: do we wish to ask question any good programmer should know the answer to (and perhaps many others), or questions that only good programmer would know the answer to ? - Matthieu M.
@David: If you write a sentence in British English like, "While I was in the underground, a lorry ran into the boot of my car, so I called my solicitor," an American may well not know that you mean, "While I was on the subway, a truck ran into the trunk of my car, so I called my lawyer." Yes, the analogy is imperfect, as human beings can figure things out from context, while the computer cannot. - Jay
@gnovice I m sorry to say this but guys like you made this question useless. COmminuty wiki questions are no more blah blah .It was a good question just to make sure you prepare the listed questions before going for an c c++ interview. Please check the related questions. You will find lot more like this. - Mohit Jain
(2) @Jay: Yes, and a one-to-one translation of "underground" to "subway", "lorry" to "truck", etc., yields idiomatic US English. Other than some vocabulary differences and spelling differences, the languages are basically alike. That makes them far closer than C (particularly C99) and C++. - David Thornley
(2) @piemesons: Please explain to me exactly how I made this question useless. I'm not responsible for the overwhelming number of incomplete and unjustified answers. And I'm quite aware of all the other incarnations of this type of question that came before. I didn't find any of them all that useful either. - gnovice
@Thornley: Okay, I'll buy that. Perhaps a better analogy would be that it is like the difference between Shakespeare's English and modern English. Much of the vocabulary is changed AND there are changes in grammar -- like in Shakespeare there are word endings to indicate tenses and person but in English we add additional words to the sentence -- but there is also much in common. Anyway, I'm not quite sure what the point of this argument is. We all know the relationship between C and C++. We're just debating how to characterize it. - Jay
@gnovice "I didn't find any of them all that useful either.".. U said that... Discussion over. - Mohit Jain
(1) @gnovice: The question was not about what you might get asked if you apply for a job. These are questions and topics you would want to ask an applicant in an interview. If you need to look up the answer to any of them, you'd better try to widely circumvent the whole topic and ask yourself who put you in the miserable situation of having to do an interview while knowing to little to properly do so. - sbi
(1) @sbi: Firstly, if this question was really only meant to help an interviewer, and not a potential interviewee or beginning programmer, then why is this line included in the post?: "Please answer questions too, so that people could learn something new regarding the language, too." Secondly, why would you want to ask these particular questions, and what sorts of answers would you expect from a good candidate? This justification and extra detail is lacking in nearly all the answers below, which is why the answers lack much value. - gnovice
@gnovice: You do have a point there. I hadn't remembered that sentence from the question. Still, this is an additional question, and while answers just listing topics might not be as helpful, they still answer the main question. - sbi
(2) voting to reopen. IMHO: downvote the bad answers, upvote the good ones, but don't close the question. - Epaga
[+36] [2010-10-14 12:55:15] Sebastian

What is the difference between

  • the stack and the heap,
  • malloc, new, new[],
  • free, delete, delete[]
  • pointers, references and pointers-to-pointers. When do you use which?

Obviously, these are fundamental aspects of C++ programming, but that is why every good C++ programmer has to know the answers to these.

Very good answers are given in:


You beat me to it..... - The Elite Gentleman
(4) +1 and new[] and delete[] plus the difference between a reference and a pointer - Let_Me_Be
Difference between realloc() and free()? - The Elite Gentleman
@Elite That's a nasty question :-) Most people probably don't even know that realloc(ptr,0); is actually free(ptr); and realloc(0,size); is actually malloc(size); - Let_Me_Be
Thanks @Let_Me_Be, even I didn't know it....granted I did C++ over 5 years ago, so it brings back good old memories. - The Elite Gentleman
+1 for putting your answer in verse. - JeremyP
@Sebastian Please answer your question in the same post. - Mohit Jain
1
[+20] [2010-10-14 13:00:17] Paul

A bit meta, but I think still worthwhile: "What are the questions every good C/C++ Developer should be able to answer?" :)

I'm serious - a good developer should be able to suggest these.


(1) so recursive of you - gtrak
(8) Sooo... what is your answer to your answer?? - kotlinski
(27) "Error: stack overflow" - Paul
(2) Who did up-vote this comment? - sbi
(2) C and C++ are different languages. In C, you can have `int class = 5;". - Thomas Matthews
2
[+17] [2010-10-14 12:54:58] sharptooth

Q: How does a pointer point to an object?

A: The pointer stores the address of that object.

Usual answer is "emmmm, it... well... points..." which is pointless.


(3) love this. there's this pointer tutorial that starts with that kind of text. i'd really recommend reading it! pastebin.com/vQbu9Lek - ianmac45
@ianmac45: That's great, especially the "C is insane too" part. - sharptooth
Good question, but i think it's very easy :) - Miro
@Miro: Yes, it is easy. It's not about knowledge, it's about understanding. You see, when a developer can craft an insane class hierarchy and use multiple virtual inheritance but can't explain that simplest thing in plain words what are the chances he will be able to answer tougher questions? - sharptooth
(18) The correct answer would be "it's implementation-specific". While present-day implementations store numeric addresses as pointers, there's no reason it couldn't be something much more elaborate (like a symbol name, or a local variable name combined with an index into the block scope/call frame, or that combined with a serial number that expires and becomes a trap after a call returns, etc.). - R..
@ianmac that link is sick... I like it... although if I didn't already know what a pointer was, I'd probably be more confused than I was when i started. - WernerCD
@R.: Sure, but it does have to fit into some integral type. Of course, the implementation could have a really big integral type. - David Thornley
(2) its phrased badly. it test the understanding if you not been able to ask a good question, then current you without telling you and then answering the question. working for you sounds not so fun. a better phrased question would be : "What a compiler do with a pointer to get to the Object?" - none
(1) @R.. : I asked a separate question about other actually used implementations: stackoverflow.com/questions/3939876/… - sharptooth
It doesn't have to fit into an integral type. It's totally possible that sizeof(void*)==64 and sizeof(long long)==8 (or smaller if CHAR_BIT>8). Of course this would be pretty inefficient.. - R..
3
[+12] [2010-10-14 13:14:52] ldx

What can happen if your destructor isn't virtual?


4
[+11] [2010-10-14 13:07:31] Prasoon Saurav

C++ :

What are Virtual Constructors in C++? :P

P.S : Notice the smiley


C (also a valid C++ question)

What's wrong with the following code?

char *p = "Sam";
p[0] = 'R';

For some reason my students seem to think that they would make a lot of sense :-D - Let_Me_Be
You mean INvalid c++ too? - Moshe
(1) @Moshe : I mean the question is valid for C++ too. :) - Prasoon Saurav
Wait...I found the solution....Segmentation Fault? lol - The Elite Gentleman
(2) @The Elite Gentleman : You get 7/10 ;) - Prasoon Saurav
@Prasoon, at least I passed... :) - The Elite Gentleman
Aren't strings in C guaranteed to be writeable? - Let_Me_Be
@Let_Me_Be : No string literals are stored in read only section. Modifying the content of any string literal invokes Undefined Behaviour. - Prasoon Saurav
@Prasoon, you actually closed this? - The Elite Gentleman
@The Elite Gentleman : I think questions like this have been asked at SO before that's why closed it. Ohh damn!! I didn't notice that it has been made CW. Voted to reopen. - Prasoon Saurav
Ok, I understand... - The Elite Gentleman
(2) assign "string" in declarations of char* is considered as declaring const. changing a const . since you use a pointer the compiler cant realy know for every possible code written if the pointer at run time still points to the const string "Sam" so the compiler let it pass and should SEGMENTATION FAULT in run time, when it finds you are trying to change a const on run time. it would be nicer if the C language would have a better error presentation such as in Java. - none
@Praason: a "virtual constructor" in C++ refers to the generalized idea of cloning, as explained by FAQ item <a href="parashift.com/c++-faq-lite/… 'What is a "virtual constructor"?'</a>. I'm mentioning this because I have the impression that folks here think that there's no such thing. - Cheers and hth. - Alf
@Alf : Yes I have read that Marshall Cline's article. However we cannot directly make a constructor virtual. I wanted to ask people why such thing is not directly possible in C++? Thats why added the smiley. You can use [text](link) to add links to comments. And its "Prasoon" sir! :) - Prasoon Saurav
5
[+9] [2010-10-14 12:59:38] Chris Card

Explain when you would use a std::vector; a std::map; a std::list and so on.


(1) Yes, but if asked, give some hints. Making up examples is hard. - Let_Me_Be
(1) It's easy and map is very different of other two, but an harder question is: "Whats difference of storing(accessing) values in vector and list?" - Miro
6
[+9] [2010-10-14 12:57:17] Matt G.

Explain the different types of casting and how they are applied in the real world.


(5) +1 because I don't know... I still WTF when I see reinterpret_cast and static_cast and dynamic_cast instead of (int) :( - meagar
@ Meagar, you can read Thinking in C++, or refer to this question stackoverflow.com/questions/332030/… - anijhaw
@anijhaw I'm badly out of touch with C++; It's been about 7 years since I considered myself primarily a C++ developer and I don't foresee getting back into it anytime soon. I'm a Ruby man now, and C++ looks like pain incarnate. Thanks though. - meagar
@meagar: To get detailed explanation of why whatever_cast is better than just (int) look for why C-style casts are bad. - sharptooth
Extra points if they can explain when it's better to use C style casts in C++ code. - Ferruccio
This can also be a good interview question by providing different scenarios and different casts and asking what each one does in that particular case, together with implicit conversions... as in what is the result of unsigned short i = 61440; cout << (int)i; - David Rodríguez - dribeas
you forgot const_cast! My favorite bad-practice-enabler :-) - ldx
7
[+8] [2010-10-14 13:07:59] Aamir

Why

void strcpy(char* dest, char* src)
{
    while(*dest++ = *src++);
}

copies the entire src string to destination?

The question was about good C/C++ programmers :)


(6) Eh... I'm usually not a fan of throwing obscure or weird looking constructs at people as a way to gauge their real-world practical competence, but I guess a good C programmer should understand it pretty quickly. - meagar
(1) Not at all obscure or weird to anyone who's read K&R. - Ferruccio
(4) char src[] = "abc"; char *dest = src + 2; Your version of strcpy would never terminate (until memory bounds occur). Of course, the "docs" could say don't do that, but it's best to be sure. - Caleb Huitt - cjhuitt
(6) This function's signature misses a const. - sbi
(3) @meagar - that's not a obscure or weird looking construct. It's a classical C and C++ construct (and a very elegant one in terms of C coding standards and programming tradition). It also elucidates syntactic and semantic rules in C and C++ that every C and C++ programmer should know. Furthermore, it is a valid interview question: I would be very suspicious of a C or C++ programmer who find this "obscure" and/or cannot answer it satisfactorily. - luis.espinal
@Caleb - you bring a good point. But one could argue that the function will terminate provided the precondition that src points to a legitimate, null-terminated string. That is, the onus is on the programmer. However, this would bring a good interview question. How does it work and why it would not work? - luis.espinal
@luis.espinal: Good points about the purpose of the question, and in general I would expect interviewees to answer with the normal bit of how it works. If someone pointed out the problems with it, they would get bonus points. However, you missed my point about never terminating: because the dest pointer points into the middle of the src pointer, the function would never terminate, even if the src pointer was originally properly null-terminated. As it continues to copy, it will continue to overwrite memory with non-null characters until it hits a bounds violation. - Caleb Huitt - cjhuitt
@sbi: Having a const is off course better but not having it is good in its own right. This can be the next question i.e., what should be the improvement to this code. - Aamir
@Caleb Huitt: There is a good discussion here on why there are no sanity checks in such an implementation. Here: stackoverflow.com/questions/3616295/… - Aamir
(1) The original question was what should be a good interview question and my question was that why does this copy the string. The discussion should be about whether it is a good question or not. Not about whether the code is correct (in every aspect) or not. BTW, gcc has a very similar implementation of strcpy as well :) which most of us use knowingly or unknowingly. - Aamir
(1) @Aamir: I don't see anything a C++ programmer should now here. I would rather say that any C++ code containing this tidbit is worth shooting down. - Matthieu M.
@Aamir: Last time I looked C had borrowed const from C++. I'm not sure about common C coding standards, but in C++ it's considered very bad style not to constify what can be constified. This is the exactly kind of interview question that always makes me cringe, because it makes the one asking the question (and probably also the ones who had answered it before me) look somewhat stupid for missing the obvious, while trying to see what I would miss. - sbi
@Matthieu M: Then you should probably shoot down a lot of strcpy's implementations which a lot of programmers use on a daily basis. I do think this is very good implementation and any good C/C++ programmer should know what is going on between the lines. - Aamir
(1) Why should a typical C++ programmer be mucking around with raw character arrays on a regular basis? I've had to do it on occasion, but the vast majority of my life is spent with the far safer std::string. For a C programmer, this question is quite good. For C++, it's just not that relevant. - nsanders
@Aamir: nsanders just answered for me. It's not a matter of being good or bad, it's just completely irrelevant for C++ :) - Matthieu M.
8
[+7] [2010-10-14 13:01:55] Abyx

They are different languages, C and C++. "C/C++" is a wrong term.


(12) Doesn't answer the question. Belongs in comments. - Ferruccio
(4) @Ferrucio - this is a correct answer to the original question - not a comment at all - KevinDTimm
This can indeed be interpreted as a genuine answer. I'm not sure it was meant that way, though. - sbi
@Ferricio - I agree with Kevin. A valid answer to a question is a correction on the question (if there is something in it to be corrected.) In other words, a poorly constructed question deserves a correcting answer. Whether people want to make it a comment, that's pretty subjective and open to interpretation. - luis.espinal
(1) I agree with the sentiment that "The C/C++ Language" does not exist but the question never actually refers to the C/C++ Language but to C/C++ Developers which I chose to interpret as "developers who have used both C and C++ and know the differences" and not as "developers who use the C/C++ language". Although the title refers to C/C++ Developers, the question itself refers to "C and C++ Developers". I guess the question is open to interpretation. - Ferruccio
9
[+6] [2010-10-14 13:16:38] Nemanja Trifunovic

My favorite question when I interview people: "What is a difference between a copy constructor and an assignment operator?"


Hmm, and what do you expect as an answer? - Let_Me_Be
@Let_Me_Be: A cctor initializes data members that previously was raw memory. An assignment op changes previously valid data members to have different values. Related: stackoverflow.com/questions/3279543/… - sbi
@sbi I was expecting an answer from the author, but if what you wrote is what he wants to hear as an answer, then I would definitely skip this one. - Let_Me_Be
@Let_Me_Be: What do you mean by "skip this one"? - sbi
@sbi I mean that if this is the requested wording, then I don't consider this question to be "A question that a good C and C++ programmer should be able to answer." - Let_Me_Be
(2) @Let_Me_Be: I disagree with you then. There's an important difference between initializing a piece of raw memory so that it becomes an actual value to be used, and assigning a new value to an existing, valid value. See, for example, stackoverflow.com/questions/1734628/1734687#1734687, stackoverflow.com/questions/3761325/3763563#3763563, or the link I already gave: stackoverflow.com/questions/3279543. - sbi
(3) I agree with @sbi. Also it is important to know what type id = value actually means i.e. it calls a constructor, not assignment. - David Rodríguez - dribeas
10
[+6] [2010-10-14 15:28:23] Blankman

Why would you choose C over more modern languages?


(1) +1. I actually see good reasons to use C, but never had the chance of meeting someone using C for any of those (or any other good reasons). - back2dos
You wouldn't. Unless you would care about your customer's execution speed instead of the time you need to write the program in C, and that you wouldn't do. - Quandary
(2) Well, you could actually be developing one of these more modern languages... - Abizern
11
[+5] [2010-10-14 12:58:13] Anthony

How would you go about implementing a template function for swapping two variables?


(10) Extra points if answer is "I wouldn't I would use std::swap". - Let_Me_Be
(1) well, I'd open up my favorite text editor, and then... - Tom
@Tom: LOL! liked it ;) - usta
Uhm, due to certain bugs in Visual C++ regarding friendship and access, it's actually a quite deep question, touching both on deep knowledge of the language, and on the difference between Theory and Practice. I currently prefer to call the member swapWith, and place a non-member swap in the global namespace. When/if Visual C++ gets its act together it would be back to straightforward code. - Cheers and hth. - Alf
12
[+5] [2010-10-14 13:11:02] Manoj R

How will you access tenth element of an array without using square brackets?


(2) char* arr = "Hello World"; char c = *(arr + 10); - Kaije
(2) @user394242: That would be the eleventh element. :-) - Thanatos
13
[+5] [2010-10-14 13:12:52] The Elite Gentleman

Interesting question I just saw:

What’s the auto keyword good for?


(4) Especially if they can differentiate between C++03 and C++0x usage. - Ferruccio
(1) Not that anyone uses it in C++03 - Tamás Szelei
(4) @Tamás Szelei: But auto could've been used in C++03. What does Item emptyItem( std::string() ); do? Correct, it declares a function. Now what does auto Item emptyItem( std::string() ); do? This time, it declares a variable. - usta
That is a good question for C programmers, too. - Jens Gustedt
(2) Isn't it totally pointless in C (I don't know C++ at all)? The storage class will be one of extern, static, auto, or register, and if it's not specified it will implicitly be auto - Nick T
14
[+5] [2010-10-14 12:54:00] Sebastian

How would you implement a working binary search? This goes for any serious programmer, I think.

PS: This question isn't really C++ specific, but I found this to be a shockingly good interview question. The concept of binary search is so simple that everybody should know it and everybody should be able to derive a working implementation from this concept.


(4) That's not a question :-D - Let_Me_Be
@Let_Me_Be Postfix "How would you..." :p - meagar
(3) Not sure it really tests their C/C++ expertise, though. Worthwhile question to assess their approach to coding generally, though. - Paul
@meager "How would you find a specific number in a sorted array?" - Let_Me_Be
I think the last time I have implemented a binary search was as a student. I'm using them almost daily, though. Well, at least I suppose that the map/set find functions I'm calling are binary. - sbi
For me, the point is not whether they can code binary search. It's just a not entirely trivial problem to see how they approch the problem (for isntance, what do they ask to clarify the requirements), how they code it, and whether they know how to test it (choice of test cases). Also it can then go into a discussion of performance, choice of algorithm etc. - Paul
@Paul: Maybe this is picking a nit, but I agree this is an excellent PROGRAMMING question, but it's not really a C/C++ question. That said, I think interviewers would be better of to ask programming questions rather than language-specific questions. If someone forgets whether & has a higher or lower operator precedence than +, he can surely look it up. If he doesn't know what a "subroutine" is or why you would want to use one ... bigger problem. - Jay
@sbi: The "I suppose" is a pretty big problem. With things like that which could kill performance, it's probably a mistake to use opaque classes which don't have a guarantee about their big-O (in both time and space) in either the language specification or the implementation's documentation. - R..
@R..: I know that the set/map find functions are O(log n) at worst. But I have never looked at any of their implementations. - sbi
@Jay: While at first I found myself nodding to your comment, then I realized that C++ is the oddball in the bunch of curly-braces languages, in that its syntax does matter a lot. A single missing & can bring a whole huge software system down to its knees and takes seemingly for ever to be found. (BTDTGTLS) You have to be very quite confident about a lot of the dark corners of the language (and it's a huge one) in order to write real good code (TM). - sbi
Binary search is really, really easy to get wrong. In Knuth's Art of Computer Programming (probably volume 3), he comments that the first appearance of binary search in print is several years earlier than the first correct appearance. This may make it a really good or a really bad programming question. - David Thornley
(1) not relevant now days. you can find the code in google in less then a minute. - none
@none How will you know if the code is correct? - Sebastian
(1) @Sebastian the same way i know a piece of code that i write is correct. - none
15
[+4] [2010-10-14 14:09:00] Donotalo
  • How do you know malloc() fails? How do you know new fails?
  • What are binary files and text files?

Why would I want to know that? If it fails, the program can't run. Does it matter why it crashes, or whether it crashes or aborts with an error message ? - Quandary
(1) @Quandary: if you know that then you can handle error situations. if you don't know that, then it can be assumed by interviewer that you don't write safe code. - Donotalo
I don't. I write elegant code, that is to say code without all that 'unnecessary' stuff around ;-)) - Quandary
(1) It depends on your platform. In Linux (with glibc at least) malloc will never return an error- if not enough memory is available the kernel will wait or just kill a process to free up memory. - CodeninjaTim
There are situations even in Linux, with glibc, in which malloc can return "out of memory": If virtual memory has run out or is too limited, or if you request more memory than exists (typically a bug), or if the kernel doesn't allow optimistic allocation. I have seen code where a simple if would have revealed a failing malloc call, and the bug that caused it. - Thanatos
16
[+4] [2010-10-14 18:15:53] jwernerny

For C++ developers:

Given class A

class A 
{
public:
    A();
    ~A();

    A operator=(A an_a);
private:
    int  i;
}

A::A()
{
}

A::~A()
{
}

A A::operator=(A an_a)
{
    i = an_a.i;
}

1) How many A's will be created by the following

   {
      A  a1, a2;

      a1 = a2;
   }

2) Why won't the code compile?

3) What's the value of i in a1 from above?

4) What's wrong with the operator= method?

5) (refinement of question from above) What is special about a static method?


17
[+4] [2010-10-14 13:53:50] Yulia Rogovaya
class A
{
...
};

A a[5];

How many times A's constructor would be called?


18
[+4] [2010-10-14 13:19:16] anijhaw

What is the difference between static in C and static in C++


There are many uses of the static keyword in C++ though, and the C version is one of them. - Adhemar
So thats what the question is supposed to ask. - anijhaw
19
[+3] [2010-10-14 13:18:40] Ian Ringrose

A questions about Virtual Destructor, why you need them etc, or a questions about why a bit of code does not work, when the need for a Virtual Destructor is part of the answer.

Also a question on when it is better to use Java and/or C# than C++, e.g does the person know what an garbage collector is.


20
[+3] [2010-10-14 15:24:20] ulaga

Most asked question in embedded companies... 1. what is the major difference b/w structure and union? 2. what is Dangling pointer? 3. Memory leakage???

More questions will be like this only....


21
[+3] [2010-10-14 13:00:02] Naveen

which containers are provided by STL and in which scenario you would use a particular container.


22
[+3] [2010-10-14 12:57:43] Kevin

I think this really goes for all programming languages, but that being said I think if you program C, C++ you should be able:

  1. Implement a recursive algorithm (or multiple different types, tail recursion etc.)
  2. Explain their affect on program execution and memory (Stack allocation etc.).

(1) Recursive, I can bet on that.I have seen quite a senior developer at a bank, who told me I was wrong because I had written a recursive function to find the height of a tree. - DumbCoder
@DumbCoder: I suppose he was wrong because your function found the depth of the tree? :) - sbi
I've had more than one discussion (read argument) where someone will angrily say "how you would implement that? It's just not possible in the code. You'll have to use the database to access all this information over and over." I finally, got tired of saying, "All you need is a recursive function to ..." and have people look at me like I was speaking another language to them. - Kevin
23
[+3] [2010-10-14 13:01:43] The Elite Gentleman
  • What is function overloading and operator overloading?
  • What is a friend class?

(1) A friend class is your own worst enemey. - Anthony
(1) As they say, keep your friends close but your enemies closer....lol - The Elite Gentleman
(1) @Shyntriir An enemy I miss every time my java compiler complains that it cant resolve the friend token - Tom
Explain when you need to use friend function instead of method when implementing an operator and why. - Let_Me_Be
I'm not saying friends aren't useful in C++, I'm just saying people tend to shoot themself in the foot more often with them. - Anthony
Who needs friends if you have C++? - Matt Joiner
24
[+2] [2010-10-14 13:02:43] ruslik

I liked this one: http://stackoverflow.com/questions/3931156/algorithm-interview-question

It's not enough just to know algorithms. Programming is about making decisions.


25
[+2] [2010-10-14 12:57:50] Ruel

Q: Differentiate C, C++, and C#.

A: Googles....


This is probably the only one of these I wouldn't be offended to be asked, and the only one I would likely ask. - Kate Gregory
26
[+2] [2010-10-14 15:41:50] luis.espinal

My favorite: how do you declare a pointer to a function returning void and taking two pointers to void as parameters?


My answer would be: "I hope this is only an interview question and there are no such things in your code base". - Nemanja Trifunovic
In that case, I would not hire you because a lot of system-level programming (right or wrong) might involves creating such constructs. It is also how you pass a comparator to the standard qsort() function (C/C++ 101). It would tell me you can work only working in ideal conditions given that most places have ugly code to one degree and another. The later must be maintained improved/refactored. It would not be pretty but it is work to be done (and this is the reality in any software shop.) Engineering is not just about creating clean pretty things, but to solve problems as well. - luis.espinal
(1) Don't get me wrong, I would not want to see constructs like that all over the place without justification. But if I were an employer, I would like to know that a person applying for a C or C++ actually knows more than a superficial exposure to pointers. I want to know that you can (within reason of course), make sense of ugly code, get through it, analyze it, and get things done if it ever comes to that. Pondering about ideal conditions does nothing without having the skills to handle ugly things if they come our way. There is more to interviews than pondering technical ideals. - luis.espinal
27
[+2] [2010-10-14 15:53:58] smailq

Which debugging tool do you use?

Explain how (break points) or (memory leak detection) work in debugging tools.


28
[+2] [2010-10-14 13:20:37] Ian Ringrose

How can you speed up compile time?

Any experienced C/C++ programmer will be able to talk about how to arrange header files etc so as to reduce the number of header files that need to be read. This then leads into some questions about good design etc…


(3) Compile time usually doesn't matters. The more important is run speed :) - Miro
@Miro... it all depends... I once was in a project for which a single file --heavily templated-- would require almost 20 minutes in a P4 with 1.5 Gb of memory (the compiler would require enough memory to trigger swapping into disk and that raised hell...) With some tweaking that was reduced to about 30 seconds, note that a big compilation delay can distract you, and that will reduce your productivity... - David Rodríguez - dribeas
@Miro, just by adding #ifndef FileName_Included to header files I have taken compile times down form over an hour on a project to about 5 minutes, so it is inportant for programmers to understand the issues. - Ian Ringrose
(3) Answer: By switching from Windows to Linux and cross-compiling under Linux. BTW: That way everything gets faster: USB speed, network transmission, default browser, folder browser, games - server - the .NET/mono framework - compiler error detection - IDE, as said, everything. - Quandary
@Quandary: Enjoy your stay. - Matt Joiner
@lan Ringrose, this is basics of creating headers :) - Miro
@Quandary Yes linux is much better than windows, but it's not very popular for now - Miro
@Miro: As long as you just use it to cross-compile it doesn't need to be popular. Neither does it for you to run a completely free server on it. - Quandary
29
[+2] [2010-10-14 13:20:58] codaddict

You can ask the candidate how would they implement an algorithm in C and later how would they do the same in C++ making use of the STL.

You can ask why did he/she choose C or C++ for the projects they've done and also ask how would they approach if the C projects had to be done in C++ and vice versa.


30
[+1] [2010-10-14 14:07:15] JeremyP

Well for a start I wouldn't ask questions whose answers can be found easily in a C or C++ reference manual or with a simple Google search unless the job for which they were being interviewed forbade using those resources (in which case the successful candidate will come to wish he wasn't).

Go for more high level questions with less clear cut or even controversial answers.

e.g. I might ask

what are some of the disadvantages of C or C++ as compared to (say) Java?

what strategies might you use to mitigate the disadvantages?

under what circumstances do the disadvantages become advantages?


This assumes that the interviewer and the interviewee are both thoroughly familiar with either C or C++ and a common other language. While you would want a senior person to be familiar with another language, there's no guarantee it's Java or C# or any other specific one. - David Thornley
That was just an example question. In any case, I would expect any competent programmer to know something about the pros and cons of reasonably common languages, particularly where they involve gotcha issues like indexing off the end of arrays and memory leaks. - JeremyP
31
[+1] [2010-10-15 13:02:00] Alan

Just what is a protected abstract virtual base pure virtual private destructor? -- Tom Cargill

Most people might not be able to answer it, but hopefully most will give it a good thought.


32
[+1] [2010-10-14 14:50:59] liaK

How can you effectively manage the memory? Can you show me through some examples...

And obviously looking for smart pointers usage..


By using the C++ garbage collector. It works. - Quandary
@ Quandary , Oh yeah... Actually am not sure if you are the one who downvoted.. If so, pls don't attend a C++ interview... - liaK
@ Quandary Is there also an OS resources collector? open file handlers collector too? Managing memory right in case of exceptions is crucial: teaches one where to put clean-up code. - MadH
What do you mean by effectively manage the memory? Examples as an answer? - Anisha Kaul
33
[0] [2010-10-14 13:29:13] MOnsDaR
  • When to use friend-classes?
  • When do Destructors have to be virtual and what is the difference to nonvirtual Dtors?
  • What do Smart-Pointers do and which types of Smartpointers exist (aiming towards shared/scoped)

There are a lot of questions which could be formulated by simply changing the tasks of C++ FAQ lite into questions: C++ FAQ lite [1]

[1] http://www.parashift.com/c++-faq-lite/

34
[-1] [2010-10-14 13:07:30] karlphillip

How to declare and initialize an int pointer to a specific memory address like 0x604768, and make it store the value 0xdead?

int* address = (int*)(void*)(uintptr_t)0x604768;
printf("Memory address is: 0x%p \n", address);

*address = 0xdead;
printf("Content of that address is: 0x%p \n", *address);

(8) I feel a sharp pain in my eye while reading this. - Let_Me_Be
(5) to add to @Let_Me_Be - while this is a correct question for certain positions, it is not a question that lives in the 'good c developer' space (and it REALLY doesn't belong in the c++ world) - KevinDTimm
excellent!!!!!! - Donotalo
(1) You failed your own interview. Your answer uses %x for printing a pointer value. Never do that. In particular on a 64 bit machine with 32 bit int... - Jens Gustedt
@Jens Would %p be better? - karlphillip
@KevinDTimm and I was thinking pointers were a strong feature of C++ and everyone should knew how to use them, heheh, my mistake. - karlphillip
(1) @karlphilip: i like this question. C++ is considered a superset of C. and pointer is indeed a part of C. this is a valid C question. - Donotalo
(3) @Donotalo: C++ is not a superset of C, even C90. In the first place, there are valid C programs that are invalid C++ programs, or do something else. In the second place, a well-written C program is not a well-written C++ program. BTW, this question relies on undefined or implementation-defined behavior. - David Thornley
@karlphillip: sure it would be better, but you'd also have to cast the pointer to void*, since in C pointers of different base type may be realized differently. But I see that you now switched to your C++ mode for that, what a pity ;-) BTW also casting an int to a pointer in C is implementation defined. Better would be a sequence (int*)(void*)(uintptr_t)0x604768. - Jens Gustedt
@Jens Thank you. - karlphillip
35