c++ - Cast ssize_t or size_t -


in source files using in project, there comparison between ssize_t , size_t variables:

ssize_t sst; size_t st;  if(sst == st){...} 

i rid of warning:

warning: comparison between signed , unsigned integer expressions 

but not sure, variable should cast other?

if((size_t)sst == st){...} 

or

if(sst == (ssize_t)st){...} 

what safer, better, cleaner? thanks

there no 1 right answer question. there several possible answers, depending on know a priori values variables may take on.

  • if know sst non-negative, can safely cast sst size_t, not change value (incidentally, happens if have no cast @ all).

  • if sst might negative know st never larger ssize_max, can safely cast st ssize_t, not change value.

  • if sst might negative, , st might larger ssize_max, neither cast correct; either 1 change value, resulting in incorrect comparison. instead, following if (sst >= 0 && (size_t)sst == st).

if you’re not absolutely certain 1 of first 2 situations applies, choose third option correct in cases.


Comments

Popular posts from this blog

Why does Ruby on Rails generate add a blank line to the end of a file? -

keyboard - Smiles and long press feature in Android -

node.js - Bad Request - node js ajax post -