views:

94

answers:

3

In my project I have turned on treat warnings as errors and compiling using the -pedantic and -ansi tags. I am using GCC compiler. In this project I have to use a third party source code which has got lot of warnings. Since I treat warnings as errors, I am having a tough time in fixing their code.

Most of the warnings are about invalid conversion from int to size_t or viceversa. In some cases, I won't be able to make both the variables same type, I mean I won't be able to change something to size_t. In such cases I am doing an explicit cast. Something like,

size_t a = (size_t) atoi(val);

I am wondering is this the correct approach? Is there any problem in doing cast like this?

If these warnings are minor, can I suppress it only on their files? How do I do the same on MSVC?

+2  A: 

Have a look at the OpenOffice wiki on the best practices for error-free code: http://wiki.services.openoffice.org/wiki/Writing_warning-free_code

They suggest static casts for these conversions, and then supply a pragma to disable warnings for a particular section of code.

Computer Guru
Thanks. I am using C not C++. `static_cast` is not available.
Appu
In that case, use your good judgement and explicit-cast away :)
Computer Guru
+6  A: 
KennyTM
Thanks. `atoi` is shown just as an example. My questions was about the casting and suppressing specific warnings on specific files.
Appu
+1 for joining the cause to eradicate all use of `atoi()`
Tim Post
That makes it clear. Thank you very much.
Appu
+1 for the diagnostic pragmas, it's exactly what I need for my Pro*C code where I have annoying warnings generated by the preprocessor that I can not fix.
tristopia
Why eradicate `atoi`? It's likely to outperform `strtoul` by several times since it doesn't have to check for overflow. If you don't care what return value you get when someone puts in a ridiculously overlarge number, `atoi` seems like a good choice.
R..
A: 

I personally consider this kind of warning idiotic and would turn it off, but the fact that you're asking about it suggests that you might be sufficiently unfamiliar with conversions between integer types and the differences in signed and unsigned behavior that the warning could be useful to you.

Back on the other hand again, I really despise [explicit] casts. The suggestion to use strtoul instead of atoi is probably a very good one. I see you commented that atoi was only an example, but the same principle applies in general: use functions that return the type you want rather than forcing a different type into the type you want. If the function is one you wrote yourself rather than a library function, this may just mean fixing your functions to return size_t for sizes rather than int.

R..