Quick question about casting basic return types
I find myself casting return types alot to silence compiler warnings and it always makes me feel like i'm doing something wrong.
This example is Objective-c
cons开发者_高级运维t char *strBuf = [anNString UTF8String];
[anOutputStream write:strBufr maxLength:len];
This goves me a compiler warning as
-UTF8String returns const char *
and -write:maxLength: takes const uint8_t *
So, knowing no better i would usually add the cast to stop the nagging and carry on my merry way.
Is this bad style (on my part), or just the way it is?
I appreciate any thoughts or advice.
There is no way around this. C, C++, and Objective-C are strongly typed languages. So, anytime there's a type conversion like that, you're going to get a compiler warning. The only way around it is to use the same types which is not always possible. It's typical. I would keep doing what you're doing. Don't ignore the warnings or turn them off because there will be one type conversion that will be an error that you will want to fix. If you turn of the warnings, you're leaving yourself vulnerable to getting a bug that will be very hard to find.
This kind of casting is kind of ugly but it's the most general way to deal with these kind of type mismatches. Some compilers provide other ways of silencing these warnings, but turning them off is a bad idea because sometimes they really matter. Casting acknowledges the difference and makes sure you've thought about any possible consequences.
(Do think about the consequences. If you just unthinkingly cast things can go badly wrong. But you're not doing that, it doesn't seem.)
精彩评论