I have just seen two interview questions for which I was unable to find any satisfying answers.The questions are
Can anyone explain the answers to me?
Thanks in advance.
Any limit is implementation-defined, but the standard requires at least 15, see 5.2.4.1
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.
2.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With