Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C interview questions [closed]

Tags:

c

I have just seen two interview questions for which I was unable to find any satisfying answers.The questions are

  1. How many levels deep can include files be nested?
  2. When should a type cast not be used?

Can anyone explain the answers to me?

Thanks in advance.

like image 464
Maddy Avatar asked Jan 28 '11 10:01

Maddy


3 Answers

  1. Any limit is implementation-defined, but the standard requires at least 15, see 5.2.4.1

  2. Same conditions as anything else: when it's wrong, and when it's unnecessary. Most famous example is probably that you shouldn't cast the return value from malloc. It's pointless[*] and it could hide an occasional bug (forgetting to #include stdlib.h). Another example is that if you randomly scatter casts between integer types, then eventually you'll suppress a compiler warning for a narrowing cast or a comparison between signed and unsigned values, that you should have paid attention to. Casts to suppress such warnings shouldn't be placed until you're sure the code is right.

[*] I used to think there was a point, because I'd write things like:

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

The cast provides some protection against a bug - using the wrong type in the sizeof. Visually I can see that the cast matches the sizeof, and the compiler checks that the variable matches the cast, so I have safety.

Now I write:

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

I don't need a check for safety, because I've certainly allocated memory of the correct size for the type of p. Well, assuming the multiplication doesn't overflow.

like image 159
Steve Jessop Avatar answered Oct 27 '22 08:10

Steve Jessop


  1. What a bad interview question! That you don't know this says something good about you. People who know things like that without looking them up in the standard are best described as eerie nerds :)

2.

  • It should preferrably not be used to remove const or volatile qualifiers.
  • It should in most cases not be used to cast between pointers pointing at different types.
  • It should not be used to cast between function pointers of different types.
like image 2
Lundin Avatar answered Oct 27 '22 07:10

Lundin


  1. As the other answer has pointed out is implementation defined, but there are problems (especially with build times) that are likely to arise from large chains. It might be a "code smell" too indicating poor encapsulation.

  2. The simplest answer is "when it's not needed", i.e. automatic, e.g. float to double, int to long (when appropriate[*]). I would assume too that it is almost certainly asking about casting from void * to something else, e.g. with malloc (comp.lang.c FAQ item).

[*] See comment

like image 2
Flexo Avatar answered Oct 27 '22 08:10

Flexo