简体   繁体   中英

C/C++ best practice to eliminate Wconversion warnings

I find the -Wconversion gcc/clang option is very useful for finding some code errors. But there are also many cases where the implicit type conversions are safe.
For example:

double a_small_double = 3.5;
/*implicitly convert double to int*/
int i = floor(a_small_double);

int len = 3;
/*implicitly convert int to size_t*/
double *p = (double*)malloc(len*sizeof(double));

Should I add an explicit type conversion every time(which is not concise at all), or just ignore them?

Yes, it is good practice to eliminate warnings and this is also the advice from Herb Sutter and Andrei Alexandrescu book C++ Coding Standards: 101 Rules, Guidelines, and Best Practices ( see excerpt ):

your compiler is your friend. If it issues a warning for a certain construct, often there's a potential problem in your code.

Successful builds should be silent (warning-free). If they aren't, you'll quickly get into the habit of skimming the output, and you will miss real problems. (See Item 2.)

To get rid of a warning: a) understand it; and then b) rephrase your code to eliminate the warning and make it clearer to both humans and compilers that the code does what you intended.

Do this even when the program seemed to run correctly in the first place. Do this even when you are positive that the warning is benign. Even benign warnings can obscure later warnings pointing to real dangers.

Granted there may be cases where this would be very hard to such as a large legacy code base but for new projects this should be your goal.

You should cast manually every time.

Also every time you convert and int to size_t, for example, you should make sure int is positive.

assert( len >= 0 ) ;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM