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.