C interview questions

I just saw two interview questions for which I could not find satisfactory answers. Questions:

  • How many levels can include files attached?
  • When should type listing be used?

Can anyone explain the answers to me?

Thanks in advance.

+8
c
source share
4 answers
  • Any limit is determined by the implementation, but the standard requires at least 15, see 5.2.4.1

  • The same conditions as everything else: when it is wrong, and when it is not necessary. The most famous example is that you should not specify the return value from malloc . This is pointless [*], and it may hide a random error (forgetting #include stdlib.h ). Another example is that if you randomly scatter castings between integer types, you will end up suppressing the compiler warning to narrow down or compare values ​​with and without a signature, which you should pay attention to. Throws to suppress such warnings should not be placed until you are sure that the code is correct.

[*] I used to think that there is a point, because I will write things like:

 foo *p = something; ... some time later ... p = (foo*) malloc(n * sizeof(foo)); 

Listing provides some error protection β€” using the wrong type in sizeof . Visually, I see that the listing matches sizeof , and the compiler checks to see if this variable matches, so I have security.

Now I write:

 p = malloc(n * sizeof(*p)); 

I don't need a security check because I definitely allocated the correct size memory for type p. Well, assuming multiplication is not overflowing.

+11
source share
  • As another answer pointed out, an implementation is defined, but there are clearly problems (especially with build time) that can arise from large chains. It could be a β€œ code smell, ” also indicating poor encapsulation.

  • The obvious answer is "when it is not necessary", that is, automatically, for example. float to double, int to long (if necessary [*]). I would also suggest that he almost certainly asks about casting from void * to something else, for example. with malloc ( comp.lang.c FAQ element ).

[*] See comment

+1
source share
  • What a bad interview question! What you do not know is something good that says about you. People who know such things without looking at them are best described as a creepy nerd :)

2.

  • It should not be used to remove constant or volatile qualifiers.
  • In most cases, it should not be used to indicate between pointers pointing to different types.
  • Cannot be used to indicate between types of function pointers of different types.
+1
source share

There is no limit to how deep it can be nested, but your compiler can end up from the stack space ... so it depends on the compiler!

0
source share

All Articles